Remove a marker from a GoogleMap

AndroidGoogle Maps

Android Problem Overview


In the new Google Maps API for Android, we can add a marker, but there is no way to (easily) remove one.

My solution is to keep the markers in a map and redraw the map when I want to remove a marker, but it is not very efficient.

private final Map<String, MarkerOptions> mMarkers = new ConcurrentHashMap<String, MarkerOptions>();

private void add(String name, LatLng ll) {
  final MarkerOptions marker = new MarkerOptions().position(ll).title(name);
  mMarkers.put(name, marker);

  runOnUiThread(new Runnable() {
    @Override
    public void run() {
      mMap.addMarker(marker);
    }
  });
}

private void remove(String name) {
  mMarkers.remove(name);

  runOnUiThread(new Runnable() {
    @Override
    public void run() {
      mMap.clear();

      for (MarkerOptions item : mMarkers.values()) {
        mMap.addMarker(item);
      }
    }
  });
}

Does anyone have a better idea?

Android Solutions


Solution 1 - Android

The method signature for addMarker is:

public final Marker addMarker (MarkerOptions options)

So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.

As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).

Solution 2 - Android

Add the marker to the map like this

Marker markerName = map.addMarker(new MarkerOptions().position(latLng).title("Title"));

Then you'll be able to use the remove method, it will remove only that marker

markerName.remove();

Solution 3 - Android

to clear all scribbles in the map use

map.clear()

Solution 4 - Android

if marker exist remove last marker. if marker does not exist create current marker

Marker currentMarker = null;
if (currentMarker!=null) {
    currentMarker.remove();
    currentMarker=null;
}

if (currentMarker==null) {
    currentMarker = mMap.addMarker(new MarkerOptions().position(arg0).
    icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}

Solution 5 - Android

If you use Kotlin language you just add this code:

Create global variables of GoogleMap and Marker types.

I use variable marker to make variable marker value can change directly

private lateinit var map: GoogleMap
private lateinit var marker: Marker

And I use this function/method to add the marker on my map:

private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    markerOptions.title(titleStr)
    marker = map.addMarker(markerOptions)
}

After I create the function I place this code on the onMapReady() to remove the marker and create a new one:

map.setOnMapClickListener { location ->
        map.clear()
        marker.remove()
        placeMarkerOnMap(location)
    }

It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: https://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude

map.setOnMarkerClickListener {marker ->
        if (marker.isInfoWindowShown){
            marker.hideInfoWindow()
        }else{
            marker.showInfoWindow()
        }
        true
    }

Solution 6 - Android

Just a NOTE, something that I wasted hours tracking down tonight...

If you decide to hold onto a marker for some reason, after you have REMOVED it from a map... getTag will return NULL, even though the remaining get values will return with the values you set them to when the marker was created...

TAG value is set to NULL if you ever remove a marker, and then attempt to reference it.

Seems like a bug to me...

Solution 7 - Android

Make a global variable to keep track of marker

private Marker currentLocationMarker;
     

//Remove old marker

            if (null != currentLocationMarker) {
                currentLocationMarker.remove();
            }
    
       

// Add updated marker in and move the camera

            currentLocationMarker = mMap.addMarker(new MarkerOptions().position(
                    new LatLng(getLatitude(), getLongitude()))
                    .title("You are now Here").visible(true)
                    .icon(Utils.getMarkerBitmapFromView(getActivity(), R.drawable.auto_front))
                    .snippet("Updated Location"));
    
            currentLocationMarker.showInfoWindow();
    
          

Solution 8 - Android

use the following code:

 mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
       @Override
       public boolean onMarkerClick(Marker marker) {
          
           marker.remove();
           return true;
       }
   });

once you click on "a marker", you can remove it.

Solution 9 - Android

Create array with all markers on add in map.

Later, use:

Marker temp = markers.get(markers.size() - 1);
temp.remove();

Solution 10 - Android

1. If you want to remove a marker you can do it as marker.remove(); alternatively you can also hide the marker instead of removing it as

 marker.setVisible(false);

and make it visible later whenever needed.
2. However if you want to remove all markers from the map Use map.clear();
Note: map.clear(); will also remove Polylines, Circles etc.
3. If you not want to remove Polylines, Circles etc. than use a loop to the length of marker (if you have multiple markers) to remove those Check out the Example here OR set them Visible false And do not use map.clear(); in such case.

Solution 11 - Android

For those that are following the example on this GoogleMaps - MapWithMarker project, you may remove the marker by doing so

override fun onMapReady(googleMap: GoogleMap?) {
    googleMap?.apply {

        // Remove marker
        clear()

        val sydney = LatLng(-33.852, 151.211)
        addMarker(
            MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney")
        )
        moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

Solution 12 - Android

Try this, it is updating the current location, and it works fine.

        public void onLocationChanged(@NonNull Location location) {               
        //here we update the location on the map
        
        LatLng myActualLocation = new LatLng(location.getLatitude(), location.getLongitude());
        
        if (markerName!=null){  // marker name is declared as a gloval variable.
            markerName.remove();
        }
        
        markerName = mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        
        // mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myActualLocation,18));
        
        }

Solution 13 - Android

If you want to delete marker when clicked, try this:

mMap.setOnMarkerClickListener(this); //mMap is googleMap
   @Override
    public boolean onMarkerClick(@NonNull Marker marker) {

        marker.remove();

        return false;
    }

https://developers.google.com/maps/documentation/android-sdk/marker

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonas SchmidView Question on Stackoverflow
Solution 1 - AndroidAnthonyView Answer on Stackoverflow
Solution 2 - AndroidEclipse22View Answer on Stackoverflow
Solution 3 - Androidfederico verchezView Answer on Stackoverflow
Solution 4 - Androiddor sharoniView Answer on Stackoverflow
Solution 5 - AndroidFaiz Azhar Ristya NugrahaView Answer on Stackoverflow
Solution 6 - AndroidSpeckpghView Answer on Stackoverflow
Solution 7 - AndroidHitesh SahuView Answer on Stackoverflow
Solution 8 - Androidkuo changView Answer on Stackoverflow
Solution 9 - AndroidElton da CostaView Answer on Stackoverflow
Solution 10 - AndroidInzimam Tariq ITView Answer on Stackoverflow
Solution 11 - AndroidNaim JamalludinView Answer on Stackoverflow
Solution 12 - Androidosnielkis roqueView Answer on Stackoverflow
Solution 13 - AndroidAlejandro Fabra SegarraView Answer on Stackoverflow