0

Here is the situation. I use Google Play Location services and MapBox API Maps. When I launch the app I immediately display current user location on A map:

private void add() {
    currentMarker = new MarkerOptions()
            .position(currentLatLng);

    mMapBoxMap.addMarker(currentMarker);
}

and update my marker position of location changes:

 private void update() {
    moveCamera();
    mMapBoxMap.clear();//Clear map so no multiple current location markers
    currentMarker = new MarkerOptions()
            .position(currentLatLng);

    mMapBoxMap.addMarker(currentMarker);
}

Then, when the current location is displayed I allow a user to click on a map and set his destination(His current location is origin):

mMapBoxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
                @Override
                public void onMapClick(@NonNull LatLng point) {
                    MarkerOptions markerOptions = new MarkerOptions().position(point);


                    mapboxMap.addMarker(markerOptions);
                    destinationLat = point.getLatitude();
                    destinationLng = point.getLongitude();


                }
            });

When I click on a map, it erases every marker and puts a new destination marker, later on a current location marker appears.

My questions:

  1. How do I add a destination marker on a map so the current location marker would still update and would not disappear everytime I click on a map? For example - I add a destination marker on a map (now there are two markers) and if I move 10 meters my current location marker moves but destination marker stays
Power3000
  • 11
  • 1
  • 7

1 Answers1

2

You need to use the reference of the marker and use removeMarker() to only remove certain markers. So have a variable:

Marker myDestinationMarker = mapboxMap.addMarker(markerOptions);

and then right above it use:

if (myDestinationMarker != null) {
  mapboxMap.removeMarker(myDestinationMarker);
}

Note two things, you can use setPosition instead of adding/removing markers and for showing user location, we offer the LocationLayer Plugin.

cammace
  • 3,138
  • 1
  • 13
  • 18
  • Thanks a lot! Will definitely take a look into that. Also one more question - – Power3000 Aug 24 '17 at 21:25
  • Also one more question: Should I deal with my current location the same way as well? Let's say I put my destination marker and my current location changes by a fraction. I don't want to lose my destination marker on a map I just want to update my location – Power3000 Aug 24 '17 at 21:32