Home > Mobile >  Remove google.maps.marker.AdvancedMarkerView from map
Remove google.maps.marker.AdvancedMarkerView from map

Time:11-19

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.

Thank you.

CodePudding user response:

There is no setMap() or other method to call on the AdvancedMarkerView 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:

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 37.39094933041195, lng: -122.02503913145092 },
    zoom: 14,
    mapId: "4504f8b37365c3d0",
  });

  const draggableMarker = new google.maps.marker.AdvancedMarkerView({
    map,
    position: { lat: 37.39094933041195, lng: -122.02503913145092 },
    draggable: true,
    title: "This marker is draggable. Click to remove.",
  });
  
  draggableMarker.addListener("click", (event) => {
  
    // Remove AdvancedMarkerView from Map
    draggableMarker.map = null;
  });
}

window.initMap = initMap;
#map {
  height: 160px;
}

p {
  font-family: Arial;
  font-size: 0.75em;
  margin: 2px 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Draggable Advanced Marker</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <p>Click on the Marker to remove it from the map.</p>
    <div id="map"></div>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=marker&v=beta"
      defer
    ></script>
  </body>
</html>

  • Related