4

I have a Marker on the map and I need to change the position of marker.

Here is my code:

public void onLocationChanged(Location location) {

    map.clear();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    if (Home_Activity.this.markerob != null) {
        Home_Activity.this.markerob.remove();
        markerob.setPosition(latLng);
    }
    latitude=location.getLatitude();
    longitude=location.getLongitude();
    CameraUpdate cameraUpdate =CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(18.0f).build());

    MarkerOptions options = new MarkerOptions().position(latLng);
    //options.title( getAddressFromLatLng( latLng ) );

    options.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(
            BitmapFactory.decodeResource(getResources(),
                    spmain.getavatarimage()), 90, 90, false)));

    //map.addMarker(new MarkerOptions().position(latLng));
    Toast.makeText(getApplicationContext(), "lat="+latLng,Toast.LENGTH_SHORT).show();

    options.position(latLng);
    map.getUiSettings().setRotateGesturesEnabled(true);
    map.animateCamera(cameraUpdate);
    map.moveCamera(cameraUpdate);
    map.addMarker(options);


    //locationManager.removeUpdates(this);
}

I have added onLocationChanged method and in that, am getting location details but not move the marker on new location.

Rinku Vashist
  • 355
  • 3
  • 14

1 Answers1

4

Check whether your map has marker added on not (for the very first time). If not then add marker and keep the reference to that marker. For subsequent calls to onLocationChanged just use the same reference to update the latitude and longitude.

    Marker myMarker;
    if(myMarker == null){
       marker = map.addMarker(options);
    } 
    else {
       marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
    }

Hope this helps. Let me know it this does not work. Will post more relevant code.

abarisone
  • 3,707
  • 11
  • 35
  • 54
apersiankite
  • 531
  • 2
  • 11