javascript - 通过 JavaScript 清除 Google Maps API 标记

标签 javascript api google-maps google-maps-api-3

我正在为我正在构建的项目使用 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/

相关文章:

javascript - 通过 next.js 中的routechange保留一些数据

javascript - 谷歌地图 : How to redirect to other points in the map?

google-maps - 获取沿 Google Maps Apiv3 中的路线服务生成的路线的所有坐标

javascript - 在另一个函数中使用一个函数的事件处理程序中声明的变量

javascript - 在 CoffeeScript 中使用数组

javascript - 有类(class)元素的 child

c# - 如何在 Google Drive API 中取消上传?

wordpress - wp rest api 获取带有元数据的帖子

javascript - OpenTok: session 和 token 有什么区别?

java - 如何限制 Google Maps API AutocompleteService 提供越界建议