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?
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.
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.
Share Improve this question edited Feb 17, 2023 at 8:14 MrUpsidown 22.5k15 gold badges82 silver badges139 bronze badges asked Nov 18, 2022 at 7:25 Christoffer JohansenChristoffer Johansen 7092 gold badges7 silver badges16 bronze badges 02 Answers
Reset to default 19There is no setMap()
or other method to call on the AdvancedMarkerElement class to toggle its visibility or remove it from the map.AdvancedMarkerView
Although it is not super clear, the documentation says:
To remove a marker from the map, set the
markerView.map
property tonull
.
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>
If you have multiple markers, you can hold a reference to them by pushing them to an array, e.g. called markers
.
var markers = [];
const marker = new google.maps.marker.AdvancedMarkerElement({
position: p,
map: map,
title: "my cool marker",
content: buildContent(myObj),
gmpClickable: true,
});
marker.data = { // <---- store additional data on the marker
name: site.name,
description: site.description
};
marker.addListener("click", () => {
toggleHighlight(marker);
});
markers.push(marker); // <--- push more markers to the markers array
Then to toggle all the markers on and off, you can do:
function toggleMarkers(){
for (var i = 0; i < markers.length; i++) {
if(markers[i].map){
markers[i].map = null;
} else {
markers[i].map = map;
}
}
}