在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:
map.clearOverlays();
我如何做到这一点在谷歌地图API v3?
看看参考API,我不清楚。
当前回答
我找到了一个简单的解决方法(我认为):
var marker = new google.maps.Marker();
function Clear(){
marker.setMap(null);
}
其他回答
只需要走过标记并将它们从map中移除,然后是空的maps标记数组:
var markers = map.markers;
for(var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
map.markers = [];
我不知道为什么,但是,设置setMap(null)到我的标记并不适用于我,当我使用DirectionsRenderer。
在我的情况下,我必须调用setMap(null)到我的DirectionsRenderer以及。
就像这样:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
if (map.directionsDisplay) {
map.directionsDisplay.setMap(null);
}
map.directionsDisplay = directionsDisplay;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
要从地图中删除所有标记,创建如下函数:
1.addMarker(location):这个函数用于在地图上添加标记
2.clearMarkers():该函数从map中移除所有标记,而不是数组中
3.setMapOnAll(map):这个函数用于在数组中添加标记信息
4.deleteMarkers():该函数通过删除对数组中所有标记的引用来删除它们。
// 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);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
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();
};
我认为V3中没有,所以我使用了上面的自定义实现。
免责声明:我没有写这段代码,但我忘记保留引用时,我合并到我的代码库,所以我不知道它来自哪里。
大多数投票的答案是正确的,但如果如果你只有一个标记(就像我曾在我的情况下),每次你需要杀死前面位置的标记,并添加一个新的然后你不需要创建整个数组的标记和管理每个推动和流行,您可以简单地创建一个变量来存储你的标记之前的位置,可以设置为null的创造新的。
//保存标记位置的全局变量。
var previousMarker;
//当添加新的标记时
if(previousMarker != null)
previousMarker.setMap(null);
var marker = new google.maps.Marker({map: resultsMap, position: new google.maps.LatLng(lat_, lang_)});
previousMarker = marker;