我正在为我正在构建的项目使用 Google Maps API v3。我已设法将标记放置在 map 上用户单击的位置,但我希望有一个清除所有按钮来删除所有标记。我在这里查看了各种答案并尝试了不同的方法。我还查阅了 Google Maps API 文档,但是我尝试过的所有方法都不起作用。应该注意的是, map 可以有多个标记。
我的代码如下:
///The function addLatLng is called when the user clicks on the Map
function addLatLng(event) {
// This code adds the marker to the map
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
///The clearall function is called when a button is clicked
function clearall() {
poly.setMap(null);//This clears the polyline that is drawn and works correctly
}
如有任何帮助,我们将不胜感激
最佳答案
根据Google Maps API doc调用 setMap 只会从 map 上删除标记,但不会删除它。如果要删除多个标记,可以按照 Google Maps API example given 进行操作。 :
1/添加标记时,将其压入数组
2/要删除所有标记:创建一个将此数组作为参数的函数,并通过 for 循环对数组的每个元素应用 setMap()。
3/要在删除后删除所有标记(即从内存中):创建一个函数来对数组中的每个标记调用 setMap(null) (根据 Google 删除标记)并从数组中删除所有标记(例如,markersArray = [])
你可以在我的第二篇引用文献中找到相应的google示例代码。
关于javascript - 通过 JavaScript 清除 Google Maps API 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28069242/