Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-maps-markersgoogle-maps-advanced-marker-element

Remove google.maps.marker.AdvancedMarkerView from map


I have a map, which populates markers based on search. I'm attempting to user the newer google maps feature AdvancedMarkerView so I can fill it with custom HTML - however, as my search updates, I want to flush the old markers and place new ones when it's called for...and I can't for the life of me figure out how to? https://developers.google.com/maps/documentation/javascript/reference/advanced-markers

The following places the custom markers. It works.

const content = document.createElement('div');
content.className = 'marker-title';
content.textContent = item.title;

const marker = new google.maps.marker.AdvancedMarkerView({
  map,
  position: item.position,
  content
});

Normally for markers, as in the old markers, I've removed them with the following code, markers.forEach((marker) => marker.setMap(null)) however this doesn't seem to work for the advanced markers. Since the marker returned when creating the advanced marker points to the element, I also tried doing a marker.remove() thinking the HTML element would be targeted, but no cigar.

I haven't been able to find any concrete examples on the Google API docs, when it comes to advanced markers, and same for others asking the same question.


Solution

  • There is no setMap() or other method to call on the AdvancedMarkerView AdvancedMarkerElement class to toggle its visibility or remove it from the map.

    Although it is not super clear, the documentation says:

    To remove a marker from the map, set the markerView.map property to null.

    Working example below:

    async function initMap() {
    
      const { Map } = await google.maps.importLibrary("maps");
      const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
      const map = new Map(document.getElementById("map"), {
        center: { lat: 37.39094933041195, lng: -122.02503913145092 },
        zoom: 14,
        mapId: "4504f8b37365c3d0",
      });
    
      const draggableMarker = new AdvancedMarkerElement({
        map,
        position: { lat: 37.39094933041195, lng: -122.02503913145092 },
        gmpDraggable: true,
        title: "This marker is draggable. Click to remove.",
      });
      
      draggableMarker.addListener("click", (event) => {
      
        // Remove AdvancedMarkerElement from Map
        draggableMarker.map = null;
      });
      
      map.addListener("click", (event) => {
      
        // Set AdvancedMarkerView position and add to Map
        draggableMarker.position = event.latLng;
        draggableMarker.map = map;
      });
    }
    
    initMap();
    #map {
      height: 160px;
    }
    <div id="map"></div>
    
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk",
        v: "weekly",
      });
    </script>