Reputation: 93
In my app I have a button to get the location programmatically. Everything went well until I realized that once I added the location marker, each time I was requesting for the location a new marker was added. Therefore I added an if statement that in my opinion is logical enough but does not work as I would like. When I get the location the first time everything is good and a marker is placed. When I push the location button a second time, the marker is deleted and no new marker is added. The app compiles on my phone with no problem. What am I doing wrong?
public void showCurrentLocation(MenuItem item) {
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;
}
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (currentLocation == null){
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_gps_view, null);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
mMap.animateCamera(update);
if (myPosition != null){
myPosition.remove();
} else {
myPosition = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_icon))
.position(latLng)
.title("I'm here!"));
}
}
}
Upvotes: 0
Views: 1319
Reputation: 18262
You are removing the Marker
from the map when the Marker
already exists but you are not adding it again.
Note that when you remove a marker from the map it is not null
, it's state is undefined.
Change your if
to update your Marker
's position when the Marker
exists:
if (myPosition != null){
myPosition.setPosition(latLng);
} else {
myPosition = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_icon))
.position(latLng)
.title("I'm here!"));
}
Upvotes: 1