Google Maps API v3:如何删除所有标记?

mp_*_*mp_ 421 html javascript google-maps google-maps-api-3

在Google Maps API v2中,如果我想删除所有地图标记,我可以简单地执行以下操作:

map.clearOverlays();
Run Code Online (Sandbox Code Playgroud)

如何在Google Maps API v3中执行此操作?

看看Reference API,我不清楚.

小智 481

只需执行以下操作:

I.声明一个全局变量:

var markersArray = [];
Run Code Online (Sandbox Code Playgroud)

II.定义一个功能:

function clearOverlays() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}
Run Code Online (Sandbox Code Playgroud)

要么

google.maps.Map.prototype.clearOverlays = function() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}
Run Code Online (Sandbox Code Playgroud)

III.在调用以下内容之前在'markerArray'中推送标记:

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});
Run Code Online (Sandbox Code Playgroud)

IV.在需要的地方调用clearOverlays();map.clearOverlays();运行.

而已!!

  • for..in循环与数组?这不能肯定..?..see:http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays (32认同)
  • 标记仍然保留在阵列中,因此它会变得越来越大.建议在循环后清除数组 (12认同)
  • 我使用`while`方法处理数组:`while(markersArray.length){markersArray.pop().setMap(null); }`.之后无需清除阵列. (11认同)
  • 或者,您可以使用marker.setVisible隐藏标记(false) (4认同)
  • 你总是可以将`markersArray`设置为一个空数组,而不是设置它的长度,我觉得有点奇怪:`markersArray = [];` (4认同)
  • `function clearOverlays() { for (i inmarkersArray)markersArray[i].setMap(null); 标记数组 = []; }` (2认同)
  • @hellatan将长度设置为零实际上会阻止垃圾收集器收集旧标记,直到它们被覆盖在数组中(或者数组本身超出范围).所以是的,你应该使用markersArray = []; 将长度设置为零不会导致内存泄漏,但如果新阵列小于旧阵列,则会浪费内存. (2认同)

Pon*_*ons 84

同样的问题.此代码不再起作用.

我已经纠正了它,用这种方式改变clearMarkers方法:

set_map(null)---> setMap(null)

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i < this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};
Run Code Online (Sandbox Code Playgroud)

文档已更新,包含有关该主题的详细信息:https://developers.google.com/maps/documentation/javascript/markers#remove

  • 但这是否清除了记忆中的标记?我意识到JavaScript具有自动垃圾收集功能,但是当调用setMap(null)时,我们怎么知道Google的API没有对标记的引用?在我的应用程序中,我添加并"删除"了大量的标记,我讨厌所有那些"删除"标记吸收内存. (4认同)
  • 现在在文档中回答了这个问题.http://code.google.com/apis/maps/documentation/javascript/overlays.html (4认同)

Mai*_*ori 47

似乎V3中还没有这样的功能.

人们建议在数组中保留对地图上所有标记的引用.然后当你想要删除em all时,只需循环遍历数组并在每个引用上调用.setMap(null)方法.

有关详细信息/代码,请参阅此问题.

我的版本:

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;

google.maps.Marker.prototype.setMap = function(map) {
    if (map) {
        map.markers[map.markers.length] = this;
    }
    this._setMap(map);
}
Run Code Online (Sandbox Code Playgroud)

代码是此代码的编辑版本http://www.lootogo.com/googlemapsapi3/markerPlugin.html我删除了手动调用addMarker的需要.

优点

  • 通过这种方式,您可以将代码保存在一个位置(不会污染命名空间).
  • 您不必再自己跟踪标记了,您可以通过调用map.getMarkers()始终在地图上找到所有标记.

缺点

  • 像我现在一样使用原型和包装器使我的代码依赖于Google代码,如果他们在源代码中进行市长更改,这将会破坏.
  • 如果你不理解它,那么如果它破坏了你将无法解决它.很有可能他们会改变任何会打破这个的东西,但仍然......
  • 如果手动删除一个标记,它的引用仍将位于标记数组中.(您可以编辑我的setMap方法来修复它,但代价是循环槽标记数组并删除引用)


rol*_*ger 23

这是YingYang于2014年3月11日15:049最初发布的最简单的解决方案,原始回复用户的原始问题

我在2.5年后使用谷歌地图v3.18使用同样的解决方案,它就像一个魅力

markersArray.push(newMarker) ;
while(markersArray.length) { markersArray.pop().setMap(null); }

// No need to clear the array after that.
Run Code Online (Sandbox Code Playgroud)


And*_*rew 21

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.addMarker = function(marker) {
    this.markers[this.markers.length] = marker;
};

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};
Run Code Online (Sandbox Code Playgroud)

我不认为V3中有一个,所以我使用了上面的自定义实现.

免责声明:我没有写这段代码,但是当我把它合并到我的代码库中时,我忘了保留一个引用,所以我不知道它来自哪里.

  • -1糟糕的风格.只创建了一个标记数组,但是在clearMarkers之后每个地图一个(导致get/set与原型的差异).令人讨厌的错误与多个地图对象. (6认同)

Jir*_*ong 17

在新版本v3上,他们建议保留在数组中.如下.

请参阅overlay-overview上的示例.

var map;
var markersArray = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
  var mapOptions = {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}
Run Code Online (Sandbox Code Playgroud)


jmb*_*cci 6

谷歌的Demo Gallery有一个关于他们如何做到这一点的演示:

http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html

您可以查看源代码以查看它们如何添加标记.

长话短说,他们将标记保存在全局数组中.清除/删除它们时,它们遍历数组并在给定的标记对象上调用".setMap(null)".

但是,这个例子显示了一个"技巧".此示例的"清除"意味着将它们从地图中删除但将它们保留在数组中,这允许应用程序快速将它们重新添加到地图中.从某种意义上说,这就像"隐藏"它们一样.

"删除"也会清除数组.


小智 6

for (i in markersArray) {
  markersArray[i].setMap(null);
}
Run Code Online (Sandbox Code Playgroud)

只在IE上工作.


for (var i=0; i<markersArray.length; i++) {
  markersArray[i].setMap(null);
}
Run Code Online (Sandbox Code Playgroud)

在chrome,firefox上工作,即......


Sph*_*ech 6

解决方案非常简单.您可以使用以下方法:marker.setMap(map);.在这里,您可以定义引脚将在哪个地图上显示.

因此,如果您设置null此方法(marker.setMap(null);),则引脚将消失.


现在,您可以编写一个函数女巫,同时使您的地图中的所有标记消失.

你只需添加将你的引脚放在一个数组中,然后使用markers.push (your_new pin)或代码声明它们,例如:

// Adds a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}
Run Code Online (Sandbox Code Playgroud)

这是一个可以在地图中设置或消除数组中所有标记的函数:

// Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }
Run Code Online (Sandbox Code Playgroud)

要消除所有标记,您应该使用以下函数调用该函数null:

// Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }
Run Code Online (Sandbox Code Playgroud)

并且,为了移除和消失所有标记,您应该重置您的标记数组,如下所示:

// Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }
Run Code Online (Sandbox Code Playgroud)

这是我的完整代码.这是我可以减少的最简单的. 请注意,您可以使用YOUR_API_KEY关键的Google API 替换代码:

<!DOCTYPE html>
<html>
  <head>
  <title>Remove Markers</title>
  <style>
     /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
     #map {
       height: 100%;
       }
  </style>
</head>
<body>

<div id="map"></div>
<p>Click on the map to add markers.</p>
<script>

  // In the following example, markers appear when the user clicks on the map.
  // The markers are stored in an array.
  // The user can then click an option to hide, show or delete the markers.
  var map;
  var markers = [];

  function initMap() {
    var haightAshbury = {lat: 37.769, lng: -122.446};

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: haightAshbury,
      mapTypeId: 'terrain'
    });

    // This event listener will call addMarker() when the map is clicked.
    map.addListener('click', function(event) {
      addMarker(event.latLng);
    });

    // Adds a marker at the center of the map.
    addMarker(haightAshbury);
  }

   // Adds a marker to the map and push to the array.
  function addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
  }

  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

  // Shows any markers currently in the array.
  function showMarkers() {
    setMapOnAll(map);
  }

  // Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

</script>
   <script async defer
    src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap">
   </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

您可以咨询google开发人员google开发人员网站上的完整文档.


Ada*_*rrh 5

rolinger的答案清晰易用.

function placeMarkerAndPanTo(latLng, map) {
      while(markersArray.length) { markersArray.pop().setMap(null); }
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
      map.panTo(latLng);

      markersArray.push(marker) ;
    }
Run Code Online (Sandbox Code Playgroud)