问题
I want to remove all markers on map when the map is clicked.
I am following the documentation here: https://developers.google.com/maps/documentation/javascript/examples/marker-remove
I've included the function:
function clearMarkers() {
setMapOnAll(null);
}
to be triggered by a click event, but I just get the error:
Uncaught ReferenceError: setMapOnAll is not defined
There is no other information in the documentation that can help me.
Can anyone point me in the right direction?
回答1:
The error is indicating that setMapOnAll does not exist in the scope
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
回答2:
Responding to your last question, you do not really need to add the markers in an array, but be aware that in the documentation example, they add the word var before adding it in the array,
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker); ...
if you only want to work with just one marker then, do not add the var word
marker = new google.maps.Marker({...
Then use marker.setMap(null); to get it out off the map.
来源:https://stackoverflow.com/questions/33621438/cannot-remove-markers-in-google-maps-js-api