2

I am listening to user location and updating marker on the map. But my code removes the previous marker and places a new marker on the new location.
What I want to do is move marker along the map from the old position to new position.

Marker playermarker;
public void onLocationChanged(final Location location) {

    if (playermarker != null) {
        playermarker.remove();
        playermarker = null;
    }
    LatLng latLng;
    latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Thats me!");
    markerOptions.icon(BitmapDescriptorFactory.fromResource(R.raw.petyr));
    playermarker = googleMap.addMarker(markerOptions);

    //Toast.makeText(getActivity(), "lokasyon degisti",Toast.LENGTH_SHORT).show();

    mydb.child("relics").addValueEventListener(new ValueEventListener() {
    HashMap < String, relic > relics = new HashMap();

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            relics.put(childSnapshot.getKey(), childSnapshot.getValue(relic.class));
        }

        for (Map.Entry < String, relic > entry: relics.entrySet()) {
            Log.d("asd", "Key = " + entry.getKey() + ", Latitude = " + entry.getValue().getLatitude() + entry.getValue().getLongitude());
            int distance = (int) Math.floor(distance(location.getLatitude(), entry.getValue().getLatitude(), location.getLongitude(), entry.getValue().getLongitude(), 0, 0));
            distancetext.setText("You are " + String.valueOf(distance) + " meters away from relic!");

        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {}
    });
}
Komal12
  • 3,340
  • 4
  • 16
  • 25

1 Answers1

0

.Don't make a new instance of marker every-time on location change, use only one instance of marker and if once instance is available then only change position of that marker instead of adding new marker everytime.Do changes like below :

if (playermarker == null) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng).
        markerOptions.title("Thats me!").
  markerOptions.icon(BitmapDescriptorFactory.fromResource(R.raw.petyr));
        playermarker = googleMap.addMarker(markerOptions);
    } else {
        playmarker.setPosition(latLng);
        // also set other things whatever you want
    }
Nilam Vaddoriya
  • 433
  • 2
  • 10