简体   繁体   中英

Two markers - current location and destination on MapBox Android

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM