Cannot remove markers in Google Maps JS API

流过昼夜 提交于 2019-12-22 00:25:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!