在谷歌地图API v2,如果我想删除所有的地图标记,我可以简单地做:

map.clearOverlays();

我如何做到这一点在谷歌地图API v3?

看看参考API,我不清楚。


在V3中似乎还没有这样的函数。

人们建议将对地图上所有标记的引用保存在一个数组中。然后当你想把它们全部删除时,只需要在数组中循环,并对每个引用调用. 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);
}

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

Pros

这样做可以使代码保持紧凑和在一个地方(不会污染名称空间)。 你不再需要自己跟踪标记你可以通过调用map。getmarkers()找到地图上的所有标记

Cons

Using prototypes and wrappers like I did now makes my code dependent on Google code, if they make a mayor change in their source this will break. If you don't understand it then you won't be able to fix it if does break. The chances are low that they're going to change anything which will break this, but still.. If you remove one marker manually, it's reference will still be in markers array. (You could edit my setMap method to fix it, but at the cost of looping trough markers array and removing the reference)

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中没有,所以我使用了上面的自定义实现。

免责声明:我没有写这段代码,但我忘记保留引用时,我合并到我的代码库,所以我不知道它来自哪里。

在两个答案中发布的“set_map”函数似乎不再在谷歌Maps v3 API中工作。

我想知道发生了什么事

更新:

似乎谷歌改变了他们的API,使“set_map”不是“setMap”。

http://code.google.com/apis/maps/documentation/v3/reference.html

同样的问题。这段代码不再工作了。

我已经纠正了它,这样改变clearMarkers方法:

set_map(空) ---> setMap(空)

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

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

简单地做以下几点:

I.声明一个全局变量:

var markersArray = [];

2定义一个函数:

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

OR

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

3在调用以下函数之前,在'markerArray'中插入标记:

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});

IV.调用clearoverlay ();或map.clearOverlays ();在任何需要的地方发挥作用。

就是这样! !

在新版本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;
  }
}

下面来自Anon的效果很好,尽管在反复清除覆盖时有闪烁。

简单地做以下几点:

I.声明一个全局变量:

var markersArray = [];

2定义一个函数:

function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

3在调用以下函数之前,在'markerArray'中插入标记:

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});

IV.在任何需要的地方调用clearoverlay()函数。

就是这样! !

希望这对你有所帮助。

我发现使用google-maps-utility-library-v3项目中的markermanager库是最简单的方法。

1. 设置标记管理器

mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function () {
    loadMarkers();
});

2. 向MarkerManager添加标记

function loadMarkers() {
  var marker = new google.maps.Marker({
            title: title,
            position: latlng,
            icon: icon
   });
   mgr.addMarker(marker);
   mgr.refresh();
 }

3.要清除标记,只需要调用MarkerManger的clearMarkers()函数

mgr.clearMarkers();

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

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

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

长话短说,他们把标记保存在一个全局数组中。当清除/删除它们时,它们循环遍历数组,并在给定的标记对象上调用". setmap (null)"。

然而,这个例子展示了一个“技巧”。对于本例,“清除”意味着将它们从映射中删除,但将它们保留在数组中,这允许应用程序快速将它们重新添加到映射中。在某种意义上,这就像“隐藏”它们。

“Delete”也会清除数组。

我刚刚尝试了kmlLayer.setMap(null),它工作。不确定这是否适用于普通的标记,但似乎工作正确。

如果你使用gmap V3插件: $(" #地图”).gmap(“removeAllMarkers”);

参见:http://www.smashinglabs.pl/gmap/documentation #后载荷

你也可以这样做:

function clearMarkers(category){ 
  var i;       

  for (i = 0; i < markers.length; i++) {                          
    markers[i].setVisible(false);        
  }    
}
for (i in markersArray) {
  markersArray[i].setMap(null);
}

只在IE上工作。


for (var i=0; i<markersArray.length; i++) {
  markersArray[i].setMap(null);
}

工作在chrome, firefox,如…

清除所有的覆盖,包括多边形,标记等…

简单的使用方法:

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}

这是我在地图应用程序中写的一个函数:

  function clear_Map() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    //var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: HamptonRoads
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}

我知道这可能是一个简单的解决方案,但这就是我所做的

$("#map_canvas").html("");
markers = [];

对我来说每次都管用。

在这里你可以找到一个如何删除标记的例子:

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es

// Add 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 setAllMap(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() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  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);
    }
});

这是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.

你是说删除是指隐藏它们还是删除它们?

如果隐藏:

function clearMarkers() {
            setAllMap(null);
        }

如果你想删除它们:

 function deleteMarkers() {
            clearMarkers();
            markers = [];
        }

注意,我使用数组标记来跟踪它们,并手动重置它。

一个简单明了的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) ;
    }

这是谷歌自己在至少一个样本中使用的方法:

var markers = [];

// Clear out the old markers.
markers.forEach(function(marker) {
  marker.setMap(null);
});
markers = [];

检查谷歌样本完整的代码示例:

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

只需要走过标记并将它们从map中移除,然后是空的maps标记数组:

var markers = map.markers;
for(var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
}
map.markers = [];

清空Googlemap

mGoogle_map.clear();

解决方法很简单。你可以使用方法:marker.setMap(map);。在这里,您定义大头针将出现在哪个映射上。

所以,如果你在这个方法中设置为null (marker.setMap(null);),大头针就会消失。


现在,你可以写一个函数女巫,而使所有的标记消失在你的地图。

您只需添加将您的大头针放入数组中并使用标记声明它们。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);
}

这是一个可以设置或消失映射中数组的所有标记的函数:

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

为了消除所有的标记,你应该调用null函数:

// 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 = [];
  }

这是我的完整代码。这是我能化简的最简单的形式。 请注意,你可以用你的密钥谷歌API替换代码中的YOUR_API_KEY:

<!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>

您可以咨询谷歌开发人员或完整的文档,也,谷歌开发人员网站。

您需要将map null设置为该标记。

var markersList = [];    

function removeMarkers(markersList) {
   for(var i = 0; i < markersList.length; i++) {
      markersList[i].setMap(null);
   }
}

function addMarkers() {
   var marker = new google.maps.Marker({
        position : {
            lat : 12.374,
            lng : -11.55
        },
        map : map
       });
      markersList.push(marker);
   }

使用这个你可以删除地图上的所有标记。

map.clear();

这对你有帮助,对我也有帮助。

要从地图中删除所有标记,创建如下函数:

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 = [];
      }

我找到了一个简单的解决方法(我认为):

var marker = new google.maps.Marker();

function Clear(){
     marker.setMap(null);
}

我使用的速记法很好地完成了这项工作。只做

    map.clear();

我尝试了所有提出的解决方案,但当我所有的标记都在一个集群下时,没有一个对我有效。 最后我写了这个:

var markerCluster = new MarkerClusterer(map, markers,
    { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
agentsGpsData[agentGpsData.ID].CLUSTER = markerCluster;

//this did the trick
agentsGpsData[agentId].CLUSTER.clearMarkers();

换句话说,如果你在一个集群中包装标记,并想要删除所有标记,你调用:

clearMarkers();

最干净的方法是遍历地图的所有功能。标记(以及多边形、折线等)存储在地图的数据层中。

function removeAllMarkers() {
  map.data.forEach((feature) => {
    feature.getGeometry().getType() === 'Point' ? map.data.remove(feature) : null
  });
}

在通过绘图管理器添加标记的情况下,最好创建一个全局标记数组,或者在创建时将标记推入数据层,如下所示:

google.maps.event.addListener(drawingManager, 'overlaycomplete', (e) => {
    var newShape = e.overlay;
    newShape.type = e.type;

    if (newShape.type === 'marker') {
      var pos = newShape.getPosition()
      map.data.add({ geometry: new google.maps.Data.Point(pos) });

      // remove from drawing layer
      newShape.setMap(null);
    }
  });

我推荐第二种方法,因为它允许您稍后使用其他google.maps.data类方法。

大多数投票的答案是正确的,但如果如果你只有一个标记(就像我曾在我的情况下),每次你需要杀死前面位置的标记,并添加一个新的然后你不需要创建整个数组的标记和管理每个推动和流行,您可以简单地创建一个变量来存储你的标记之前的位置,可以设置为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;