How to draw route direction from current location to destination - java

How to draw a route direction from current location to the destination using Google Maps API v2?
public class Trazo_Rutas extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trazo__rutas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
//AutoComplete search bar
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//get latlong for corners for specified place
LatLng corner1 = new LatLng(25.64379, -103.60966);
LatLng corner2 = new LatLng(25.64317, -103.20935);
LatLng corner3 = new LatLng(25.43872, -103.61104);
LatLng corner4 = new LatLng(25.43748, -103.20866);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(corner1);
builder.include(corner2);
builder.include(corner3);
builder.include(corner4);
LatLngBounds bounds = builder.build();
//add them to builder
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
// 20% padding
int padding = (int) (width * 0.20);
//set latlng bounds
mMap.setLatLngBoundsForCameraTarget(bounds);
//move camera to fill the bound to screen
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (userLocation != null) {
userLocation.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Tu ubicación");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
userLocation = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
This code is only for adding a marker.
How to draw the direction from current location to destination?

There are multiple ways of doing that..
Using browser, pass source and destination
public void showDirections(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
}
Using Projection inside map See How to draw straight path between two points. Its not perfect solution for your issue, But you will get idea.

Related

How do I draw a repeatable polyline on googleMap?

'''
public class GpsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PRIORITY_HIGH_ACCURACY = 100;
private GoogleMap mMap;
private static final int PERMISSIONS_FINE_LOCATION = 99;
Location loc;
LatLng curPo;
boolean state = false;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
Button rstart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationRequest = LocationRequest.create()
.setInterval(5000)
.setPriority(PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(5);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(GpsActivity.this);
setContentView(R.layout.activity_gps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
rstart = findViewById(R.id.rstart);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
changeState();
}
});
askforPermission();
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(checkPermission()){
mMap.setMyLocationEnabled(true);
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
if (checkPermission()) {
Log.d(TAG, "onStart : call mFusedLocationClient.requestLocationUpdates");
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
if (mMap!=null)
mMap.setMyLocationEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
if(fusedLocationProviderClient != null){
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
}
// Methods
private void askforPermission(){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
LocationCallback mCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
for(Location location : locationResult.getLocations()){
setCurrentLocation(location);
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest,mCallback,null);
fusedLocationProviderClient.removeLocationUpdates(mCallback);
}else{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private boolean checkPermission() {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED ) {
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSIONS_FINE_LOCATION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
askforPermission();
}else{
Toast.makeText(this,"this App requires permission for gps", Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void setCurrentLocation(Location location) {
LatLng startLatLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 15);
mMap.moveCamera(cameraUpdate);
//mMap.addMarker(new MarkerOptions().position(currentLatLng)); //확인용
}
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
public void changeState() {
if(!state){
mMap.clear();
state = true;
Toast.makeText(this, "Recording Start", Toast.LENGTH_SHORT).show();
if(state && checkPermission()){
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
addMarkerSingle();
}
rstart.setText("Stop");
}else{
state = false;
Toast.makeText(this, "Recording Stop", Toast.LENGTH_SHORT).show();
if(!state) {
addMarkerSingle();
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
rstart.setText("Start");
}
}
public void addMarkerSingle(){
if(checkPermission()){
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
double markerLat = location.getLatitude();
double markerLong = location.getLongitude();
LatLng startEnd = new LatLng(markerLat, markerLong);
mMap.addMarker(new MarkerOptions().position(startEnd));
}
});
}
}
}
'''
Hi I'm a noob to programming this is my first project after learning 3month and I have no
idea how to make it happen
I want to draw a real time foot print tracking polyline but no matter what I do, it never works I tried to get a LatLng and draw a polyline from inside LocationCallback and I also tried making a new Thread to handle it I tried in onCreate, onMapReady and everything but it never works. so I came here to ask how you guys handle these kindda stuff.
I know it's shitty code and I know I suck plz understand, among 3 month of lessons java class went for only 2weeks we never even got to using Thread part, plz help me out.
the code above is code with out any errors. I can check my location on real time and there is start marker and end marker. What I want to do is track the paths I walked and show it with polyline. not after i finish I want it to keep updating real time
Thank you for your time and help
You need to store/cache the list of LatLng you get from LocationCallback.
Create a property
private ArrayList<String> myPath = new ArrayList<>();
Now every time a new location is received in the LocationCallback you add it to the myPath and update your map
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
//add this
myPath.add(loc)
updateMap()
}
}
};
Your updateMap() method might look like this
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(myPath);
polylineOptions.width(10f)
.color(Color.RED)
.geodesic(true);
if(mMap != null {
mMap.addPolyline(polylineOptions);
}
polyLineCollection.addPolyline(polylineOptions)
tempLine.tag = MarkerID(line.id, line.layerId , null)
try this code
//...
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> savedLocation = locationResult.getLocations();
Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
.clickable(false);
for(int i = 0; i<savedLocation.size; i++){
polyline1.add(new LatLng(savedLocation[i].latitude, savedLocation[i].longitude)));
}
// Store a data object with the polyline, used here to indicate an arbitrary type.
polyline1.setTag("A");
// Style the polyline.
stylePolyline(polyline1);
if(savedLocation.size() > 0){
loc = savedLocation.get(savedLocation.size() - 1);
curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
String curPoLog = "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude();
Log.d(TAG,"OnLocationResult: " + curPoLog);
setCurrentLocation(loc);
}
}
};
...//

How to assign value to GoogleMap

How do i assign a value to GoogleMap mMap;
it is showing null pointer exception when trying to run my activity and i think that means i have to assign a value to mMap how do i do that
this is the error i am getting
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
this is my code
public class RideHailActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private final int MY_PERMISSION_REQUEST_CODE = 7000;
private final int PLAY_SERVICES_RES_REQUEST = 7001;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference reference;
GeoFire geoFire;
Marker current;
MaterialAnimatedSwitch locationSwitch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ride_hail);
MapsInitializer.initialize(getApplicationContext());
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) mapFragment.getMapAsync(this);
locationSwitch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
locationSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline) {
startLocationUpdates();
displayLocation();
}else {
stopLocationUpdates();
current.remove();
}
}
});
reference = FirebaseDatabase.getInstance().getReference("biker");
geoFire = new GeoFire(reference);
setUpLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}else {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
if (locationSwitch.isChecked()) {
final double latitude = lastLocation.getLatitude();
final double longitude = lastLocation.getLongitude();
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (current != null) current.remove();
current = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike))
.position(new LatLng(latitude, longitude))
.title("You"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),15.0f));
rotateMarker(current, -360, mMap);
}
});
}
}
else {
Log.d("ERROR", "Cannot get your location");
}
}
private void rotateMarker(final Marker current, final float i, GoogleMap googleMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = current.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
current.setRotation(-rot >180?rot/2:rot);
if (t<1.0) {
handler.postDelayed(this,16);
}
}
});
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
displayLocation();
}
}
thanks is advance
In your activity activity Xml,add a Mapview then initialize
MapView mMapView;
static final GoogleMap[] googleMap = new GoogleMap[1];
static LatLng mypos = new LatLng(0, 0);
void init_map(final Activity act, Bundle saved_inst)
{
//you need to have intialized mMapview from your layout
mMapView.onCreate(saved_inst);
mMapView.onResume(); // needed to get the map to display immediately
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap[0] = mMap;
if (ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(act,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
99);
} else {
googleMap[0].setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mypos = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(mypos).zoom(10).build();
googleMap[0].animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
googleMap[0].setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
}
});
googleMap[0].setMyLocationEnabled(true);
googleMap[0].setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
});
}
you then call it like this from your oncreate
init_map(this,savedInstanceState);
this is assuming you have already set the api key from the manifest
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_api_key" />
to get started on geting an API key see https://developers.google.com/maps/documentation/android-sdk/get-api-key

Draw Polyline on google map while Running /Driwing

Draw Polyline on google map while Running /Drawing
I'm Creating a where the users can track there a path from where to where he just ran. I have tried Following code it's working but while running it getting start to lagging can anyone tell me where I doing wrong.
To draw polyline I'm refreshing map after some interval
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private ArrayList<LatLng> points =new ArrayList<>(); //added
Polyline line; //added
/* private final View.OnClickListener clickListener = view -> {
if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
animateCamera(currentLocation);
};
*/
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && googleMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
// findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
if (currentLocationMarker != null){
System.out.println("LastMArkerPostion" + currentLocationMarker.getPosition());
points.add(currentLocationMarker.getPosition());
currentLocationMarker.remove();
}
PolylineOptions options = new PolylineOptions();
for (int i = 0 ; i<points.size() ; i++ ){
options.add(points.get(i)).width(15).color(Color.BLUE).geodesic(true);
googleMap.addPolyline(options);
}
Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_green_car_marker, null);
Bitmap bit = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bit);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
currentLocationMarker = googleMap.addMarker(new MarkerOptions().icon( BitmapDescriptorFactory.fromBitmap(bit)).position(latLng));
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
googleMap = null;
}
}
Thanks in advance
Solution
After so many research I found the solution on a GitHub repository
I have made some changes in original code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapsActivity";
public GoogleMap mMap;
private ArrayList<LatLng> points;
Polyline line;
Marker now;
double lat1;
double lon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
points = new ArrayList<LatLng>();
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (!mMap.isMyLocationEnabled())
mMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if (myLocation != null) {
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
lat1=myLocation.getLatitude();
lon1=myLocation.getLongitude();
mMap.addMarker(new MarkerOptions()
.position(userLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("Welcome ")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);
Log.v(TAG, "Lat1=" + lat1);
Log.v(TAG, "Long1=" + lon1);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 20), 1500, null);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,0, new LocationListener() {
#Override
public void onLocationChanged(Location myLocation) {
// Getting latitude of the current location
double latitude = myLocation.getLatitude();
// Getting longitude of the current location
double longitude = myLocation.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Adding new marker
/* now = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(latLng).title("New")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);*/
// Showing the current location in Google Map
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
// mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
//Draw polyline
drawPolygon(latitude, longitude);
// Toast.makeText(MapsActivity.this, String.valueOf(latitude)+String.valueOf(longitude), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
});
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private void drawPolygon( double latitude, double longitude) {
List<LatLng> polygon = new ArrayList<>();
//old lat and long
polygon.add(new LatLng(lat1, lon1));
//new lat and long
polygon.add(new LatLng(latitude,longitude));
mMap.addPolygon(new PolygonOptions()
.addAll(polygon)
.strokeColor(Color.parseColor("#03A9F4"))
.strokeWidth(15)
.fillColor(Color.parseColor("#B3E5FC"))
);
lat1=latitude;
lon1=longitude;
}
}
Full code available on
Github

display current location in MapFragment

I have a location class which creates an instance on MapFragment, and dependant on which activity the map is created from, will drop a different marker. I would also like the map to display a marker for the phones current location.
I'm assuming I can do something like this, but I cant work out how to get and update the phones current coordinates and assign that to myLocation.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
MapFragment googleMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
googleMap.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap nMap){
if(MainMenu.bkSource == true) {
LatLng bkLatLng = new LatLng(54.5816008, -5.9651271);
LatLng myLocation = new LatLng(???);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("Burger King, Boucher Road"));
nMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here");
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.kfcSource == true){
LatLng bkLatLng = new LatLng(54.5771914, -5.9620562);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("KFC, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.mcdSource == true){
LatLng bkLatLng = new LatLng(54.5879486, -5.9580009);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("McDonald's, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
}
Here is an example Fragment that extends SupportMapFragment, on launch it will get the user's current location, place a Marker, and zoom in:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
Since the Location permission request needs to go through the Activity, you will need to route the result from the Activity to the Fragment's onRequestPermissionsResult() method:
public class MainActivity extends AppCompatActivity {
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = new MapFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.mapframe, mapFragment);
transaction.commit();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
The layout just contains a FrameLayout where the MapFragment goes.
activity_main.xml:
Use the following code for get current location:
#Override
public void onMapReady(GoogleMap googleMap) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
If you want to add marker in current Location try this:
1.Implement LocationListener In your Activity.
2.Update LocationRequest:
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
3.create your marker on onLocationChanged(Location location)
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
//place marker at current position
//mGoogleMap.clear();
Marker currLocationMarker;
if (currLocationMarker != null) {
currLocationMarker.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position.......");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
currLocationMarker = mMap.addMarker(markerOptions);
}
}

Android : Display Markers in MapActivity

This code below currently shows location of device. I am getting JSON from URL, and parsing it below. I want to display this as Markers in my MapActivity. I am getting java.lang.NullPointerException on mMap.addMarket(_markeroptions).
I am getting JSON data, that part is working, just not able to display it on Map. Your guidance will be helpful.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
// Add stDisplayListView code here
JSONArray jsonArray;
String json_string;
// End stDisplayListView
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
Marker doctorLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// int x =_st.jsonArray.length();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
// int count = _st.doctorAdapter.getCount();
// int i =1;
json_string = getIntent().getExtras().getString("JSON_DTA");
try {
int count =0 ;
//jsonObject = new JSONObject(json_string);
jsonArray = new JSONArray(json_string);
int _id;
String _doctorname;
String _doclat;
String _doclong;
//List<Marker> markers = new ArrayList<Marker>();
while(count < jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
_id = JO.getInt("id");
_doctorname = JO.getString("doctorname");
_doclat = JO.getString("latitude");
_doclong = JO.getString("longitude");
count++;
Double d = Double.parseDouble(_doclat);
Double e = Double.parseDouble(_doclong);
LatLng latLng = new LatLng(d,e);
//mMap = googleMap;
MarkerOptions _markeroptions = new MarkerOptions()
.position(latLng);
mMap.addMarker(_markeroptions);
}
}
catch (JSONException e) {
e.printStackTrace();
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
// int a = _st.json_string.length();
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
//ParseJSONdata parseJSONdata = new ParseJSONdata();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
//You can add here other case statements according to your requirement.
}
}
When onMapReady() method is call you used map Object without initialization and after you initialize, so then have return null pointer.
mMap = googleMap; //Map initialize by this line
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
this code put above try catch in onMapReady() method and run your code.

Categories