简体   繁体   English

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

[英]Google Maps API v3: How to remove all markers?

In Google Maps API v2, if I wanted to remove all the map markers, I could simply do:在 Google Maps API v2 中,如果我想删除所有地图标记,我可以简单地执行以下操作:

map.clearOverlays();

How do I do this in Google Maps API v3 ?如何在 Google Maps API v3 中执行此操作?

Looking at the Reference API , it's unclear to me.查看Reference API ,我不清楚。

Simply do the following:只需执行以下操作:

I. Declare a global variable:一、声明一个全局变量:

var markersArray = [];

II.二、 Define a function:定义一个函数:

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;
}

III.三、 Push markers in the 'markerArray' before calling the following:在调用以下命令之前,在“markerArray”中推送标记:

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

IV.四、 Call the clearOverlays();调用clearOverlays(); or map.clearOverlays();map.clearOverlays(); function wherever required.在任何需要的地方发挥作用。

That's it!!而已!!

Same problem.同样的问题。 This code doesn't work anymore.此代码不再起作用。

I've corrected it, change clearMarkers method this way:我已经更正了,以这种方式更改 clearMarkers 方法:

set_map(null) ---> setMap(null) 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();
};

Documentation has been updated to include details on the topic: https://developers.google.com/maps/documentation/javascript/markers#remove文档已更新以包含有关该主题的详细信息: https : //developers.google.com/maps/documentation/javascript/markers#remove

It seems that there is no such function in V3 yet. V3好像还没有这个功能。

People suggest to keep references to all markers you have on the map in an array.人们建议将地图上所有标记的引用保留在数组中。 And then when you want to delete em all, just loop trough the array and call .setMap(null) method on each of the references.然后当你想全部删除它们时,只需循环遍历数组并在每个引用上调用 .setMap(null) 方法。

See this question for more info/code. 有关更多信息/代码,请参阅此问题。

My version:我的版本:

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);
}

The code is edited version of this code http://www.lootogo.com/googlemapsapi3/markerPlugin.html I removed the need to call addMarker manually.该代码是此代码的编辑版本http://www.lootogo.com/googlemapsapi3/markerPlugin.html我删除了手动调用 addMarker 的需要。

Pros优点

  • Doing this way you keep the code compact and in one place (doesn't pollute the namespace).这样做可以使代码紧凑并集中在一个地方(不会污染命名空间)。
  • You don't have to keep track of the markers yourself anymore you can always find all the markers on the map by calling map.getMarkers()您不必再自己跟踪标记,您始终可以通过调用 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.像我现在一样使用原型和包装器使我的代码依赖于 Google 代码,如果他们对源代码进行了重大更改,这将会中断。
  • 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) (你可以编辑我的 setMap 方法来修复它,但代价是循环低谷标记数组并删除引用)

This was the most simple of all the solutions originally posted by YingYang Mar 11 '14 at 15:049 under the original response to the users original question这是YingYang 于 2014 年 3 月 11 日 15:049在对用户原始问题的原始回复下最初发布的所有解决方案中最简单的

I am using his same solution 2.5 years later with google maps v3.18 and it works like a charm 2.5 年后,我在 google maps v3.18 上使用了他的相同解决方案,它的作用就像一个魅力

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

// No need to clear the array after that.
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();
};

I don't think there is one in V3 so I used the above custom implementation.我认为 V3 中没有,所以我使用了上面的自定义实现。

Disclaimer: I did not write this code but I forgot to retain a reference when I merged it into my codebase so I don't know where it came from.免责声明:这段代码不是我写的,但我在将它合并到我的代码库中时忘记保留引用,所以我不知道它来自哪里。

On the new version v3, They recommended to keep in arrays.在新版本 v3 上,他们建议保留在数组中。 as following.如下。

See sample at 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;
  }
}
for (i in markersArray) {
  markersArray[i].setMap(null);
}

is only working on IE.只在 IE 上工作。


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

working on chrome, firefox, ie...在 chrome、firefox 上工作,即...

A clean and easy application of rolinger's answer.罗林格答案的简洁应用。

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) ;
    }

The solution is quite easy.解决方法很简单。 You may use the method: marker.setMap(map);您可以使用以下方法: marker.setMap(map); . . Here, you define on which map the pin will appear.在这里,您定义图钉将出现在哪个地图上。

So, if you set null in this method ( marker.setMap(null); ), the pin will disappear.因此,如果您在此方法中设置nullmarker.setMap(null); ),该引脚将消失。


Now, you can write a function witch while make disappear all markers in your map.现在,您可以编写一个函数,同时使地图中的所有标记消失。

You just add to put your pins in an array and declare them with markers.push (your_new pin) or this code for example:您只需添加以将您的引脚放入一个数组中并使用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);
}

This is a function witch can set or disappear all the markers of your array in the map:这是一个函数,可以设置或消失地图中数组的所有标记:

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

To disappear all your markers, you should call the function with null :要消失所有标记,您应该使用null调用该函数:

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

And, to remove and disappear, all your markers, you should reset your array of markers like this:而且,要删除和消失所有标记,您应该像这样重置标记数组:

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

This is my complete code.这是我的完整代码。 It's the simplest I could reduce to.这是我能简化到的最简单的。 Be care full you may replace YOUR_API_KEY in the code by your key google API:小心你可以用你的关键谷歌 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>

You may consult google developer or the complete documentation on, also, google developer web site .您可以在google developer 网站上咨询google developer或完整的文档。

Google's Demo Gallery has a demo on how they do it: Google 的 Demo Gallery 有一个关于他们如何做的演示:

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

You can view the source code to see how they add markers.您可以查看源代码以了解它们如何添加标记。

Long story short, they keep the markers in a global array.长话短说,他们将标记保存在全局数组中。 When clearing/deleting them, they loop through the array and call ".setMap(null)" on the given marker object.清除/删除它们时,它们会遍历数组并在给定的标记对象上调用“.setMap(null)”。

However, this example shows one 'trick'.然而,这个例子展示了一个“技巧”。 "Clear" for this example means removing them from the map but keeping them in the array, which allows the application to quickly re-add them to the map.本示例中的“清除”意味着将它们从地图中删除,但将它们保留在数组中,这允许应用程序快速将它们重新添加到地图中。 In a sense, this acts like "hiding" them.从某种意义上说,这就像“隐藏”它们。

"Delete" clears the array as well. “删除”也会清除数组。

The " set_map " function posted in both answers appears to no longer work in Google Maps v3 API.两个答案中发布的“ set_map ”函数似乎不再适用于 Google Maps v3 API。

I wonder what happened我不知道发生了什么

Update:更新:

It appears Google changed their API such that " set_map " is not " setMap ".谷歌似乎改变了他们的 API,使得“ set_map ”不是“ setMap ”。

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

Here you can find an example of how to remove markers:您可以在此处找到有关如何删除标记的示例:

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es 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 = [];
}

The following from Anon works perfectly, although with flickers when repeatedly clearing the overlays.以下来自 Anon 的作品完美无缺,尽管在反复清除叠加层时会闪烁。

Simply do the following:只需执行以下操作:

I. Declare a global variable:一、声明一个全局变量:

var markersArray = [];

II.二、 Define a function:定义一个函数:

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

III.三、 Push markers in the 'markerArray' before calling the following:在调用以下命令之前,在“markerArray”中推送标记:

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

IV.四、 Call the clearOverlays() function wherever required.在需要的地方调用clearOverlays()函数。

That's it!!而已!!

Hope that will help you.希望这会帮助你。

I found using markermanager library in the google-maps-utility-library-v3 project as the easiest way.我发现在 google-maps-utility-library-v3 项目中使用 markermanager 库是最简单的方法。

1. Set up the MarkerManager 1.设置MarkerManager

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

2. Add markers to the MarkerManager 2. 在 MarkerManager 中添加标记

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

3. To clear markers you just need to call the MarkerManger's clearMarkers() function 3. 要清除标记,您只需要调用 MarkerManger 的clearMarkers()函数

mgr.clearMarkers();

You can do it this way too:你也可以这样做:

function clearMarkers(category){ 
  var i;       

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

To clear of all the overlays including polys, markers, etc...清除所有叠加层,包括多边形、标记等...

simply use:只需使用:

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

Here is a function that I wrote to do it form me on a map application:这是我在地图应用程序上编写的一个函数:

  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"));
}

To remove all markers from map create functions something like this:要从地图中删除所有标记,请创建如下函数:

1.addMarker(location): this function used to add marker on map 1.addMarker(location):该函数用于在地图上添加标记

2.clearMarkers(): this function remove all markers from map, not from array 2.clearMarkers():该函数从地图中删除所有标记,而不是从数组中删除

3.setMapOnAll(map): this function used to add markers info in array 3.setMapOnAll(map):该函数用于在数组中添加标记信息

4.deleteMarkers(): this function Deletes all markers in the array by removing references to them. 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 = [];
      }

The cleanest way of doing this is to iterate over all the features of the map.最简洁的方法是迭代地图的所有特征。 Markers (along with polygons, polylines, ect.) are stored in the data layer of the map.标记(连同多边形、折线等)存储在地图的数据层中。

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

In the case that the markers are being added via drawing manager , it's best to create a global array of markers or pushing the markers into the data layer on creation like so:在通过绘图管理器添加标记的情况下,最好创建一个全局标记数组或在创建时将标记推入数据层,如下所示:

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);
    }
  });

I recommend the second approach as it allows you to use other google.maps.data class methods later.我推荐第二种方法,因为它允许您稍后使用其他 google.maps.data 类方法。

I have just tried this with kmlLayer.setMap(null) and it worked.我刚刚用 kmlLayer.setMap(null) 试过这个,它奏效了。 Not sure if that would work with regular markers but appears to work correctly.不确定这是否适用于常规标记,但似乎可以正常工作。

This is the method Google themselves use in at least one sample:这是 Google 自己在至少一个示例中使用的方法:

var markers = [];

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

Check Google sample for complete code example:检查谷歌示例以获取完整的代码示例:

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

I dont' know why, but, setting setMap(null) to my markers didn't work for me when I'm using DirectionsRenderer .我不知道为什么,但是,当我使用DirectionsRenderer时,将setMap(null)设置为我的标记对我不起作用。

In my case I had to call setMap(null) to my DirectionsRenderer as well.在我的情况下,我也必须将setMap(null)调用到我的DirectionsRenderer

Something like that:类似的东西:

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);
    }
});

Just walk over markers and remove them from map, empty maps markers array after that:只需走过标记并将它们从地图中删除,然后清空地图标记数组:

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

只需清除谷歌地图

mGoogle_map.clear();

I've tried all of proposed solutions, but nothing worked for me while all my markers were under a cluster.我已经尝试了所有建议的解决方案,但是当我所有的标记都在一个集群下时,没有任何效果对我有用。 Eventually I just put this:最后我只是把这个:

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();

In other words, if you wrap markers in a cluster and want to remove all markers, you call:换句话说,如果您将标记包装在一个集群中并想要删除所有标记,您可以调用:

clearMarkers();

Most voted answer at top is correct but in case if you have only one marker at a time (like I had in my situation) and every time you need to kill the previous location of that marker and add a new one then you don't need to create whole array of markers and manage it on every push and pop, you can simply just create a variable to store your marker's previous location and can set that to null on creation of new one.顶部投票最多的答案是正确的,但如果您一次只有一个标记(就像我的情况一样)并且每次您需要杀死该标记的前一个位置并添加一个新位置,那么您就不需要需要创建整个标记数组并在每次推送和弹出时对其进行管理,您只需创建一个变量来存储标记的先前位置,并可以在创建新标记时将其设置为 null。

// Global variable to hold marker location. // 保存标记位置的全局变量。

var previousMarker; var previousMarker;

//while adding a new marker //同时添加一个新的标记

    if(previousMarker != null)
previousMarker.setMap(null);

var marker = new google.maps.Marker({map: resultsMap, position: new google.maps.LatLng(lat_, lang_)});
previousMarker = marker;

You mean remove as in hiding them or deleting them?你的意思是删除隐藏它们或删除它们?

if hiding:如果隐藏:

function clearMarkers() {
            setAllMap(null);
        }

if you wish to delete them:如果您想删除它们:

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

notice that I use an array markers to keep track of them and reset it manually.请注意,我使用数组标记来跟踪它们并手动重置它。

You need to set map null to that marker.您需要将 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);
   }

I found simple solution (I think) :我找到了简单的解决方案(我认为):

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

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

I use a shorthand that does the job well.我使用的速记可以很好地完成工作。 Just do做就是了

    map.clear();

Using this you can remove all marker from map . 使用此功能,您可以从地图中删除所有标记。

map.clear();

This would help you ,it help me.. 这会对你有所帮助,它对我帮助..

if you use the gmap V3 plugin: $("#map").gmap("removeAllMarkers");如果您使用 gmap V3 插件: $("#map").gmap("removeAllMarkers");

see: http://www.smashinglabs.pl/gmap/documentation#after-load见: http : //www.smashinglabs.pl/gmap/documentation#after-load

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM