Move marker with gps in google map android
First of All implement LocationListener in your Activity then
if you need to show only one Marker(update position of Marker), use this :
private Marker currentPositionMarker = null;
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
// mMap.clear(); // Call if You need To Clear Map
if (currentPositionMarker == null)
currentPositionMarker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.position(latLng)
.zIndex(20));
else
currentPositionMarker.setPosition(latLng);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
or if you want to add a new marker every time :
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.position(latLng)
.zIndex(20));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
if location was changed rapidly, it would take a couple of seconds for your app to update its location marker
You can use below code to update position of the Marker
public void onLocationChanged(Location location) {
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(lattitude, longitude);
if(mCurrLocationMarker!=null){
mCurrLocationMarker.setPosition(latLng);
}else{
mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("I am here");
}
tv_loc.append("Lattitude: " + lattitude + " Longitude: " + longitude);
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
You don't need to clear map every time. You can do it by Marker object that is returned when adding Marker to Map. Hope it will help you.