首页 文章

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

提问于
浏览
408

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

map.clearOverlays();

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

看着Reference API,我不清楚 .

30 回答

  • 2

    你也可以这样做:

    function clearMarkers(category){ 
      var i;       
    
      for (i = 0; i < markers.length; i++) {                          
        markers[i].setVisible(false);        
      }    
    }
    
  • 467

    只需执行以下操作:

    I.声明一个全局变量:

    var markersArray = [];
    

    II . 定义一个功能:

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

    要么

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

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

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

    IV . 在需要的地方调用 clearOverlays();map.clearOverlays(); 函数 .

    而已!!

  • 45

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

    我已经纠正了它,用这种方式改变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();
    };
    

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

  • 20

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

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

    See this question for more info/code.

    我的版本:

    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的需要 .

    优点

    • 这样做可以使代码紧凑并保存在一个地方(不会污染命名空间) .

    • 您不必再自己跟踪标记了,您可以通过调用map.getMarkers()始终在 Map 上找到所有标记

    缺点

    • 像我现在一样使用原型和包装器使我的代码依赖于Google代码,如果他们在源代码中进行市长更改,这将会破坏 .

    • 如果你破坏了,你就不能修复它 . 很有可能他们会改变任何会打破这个的东西,但仍然......

    • 如果手动删除一个标记,它的引用仍将在标记数组中 . (您可以编辑我的setMap方法来修复它,但代价是循环槽标记数组并删除引用)

  • 3

    这是最初由 YingYang Mar 11 '14 at 15:049 根据用户原始问题的原始回复发布的所有解决方案中最简单的

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

    markersArray.push(newMarker) ;
    while(markersArray.length) { markersArray.pop().setMap(null); }
    
    // No need to clear the array after that.
    
  • 83
    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中有一个,所以我使用了上面的自定义实现 .

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

  • 21

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

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

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

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

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

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

    “删除”也会清除数组 .

  • 6
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    

    只在IE上工作 .


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

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

  • 3

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

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


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

    您只需添加将引脚放入数组中并使用 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);
    }
    

    这是一个可以在 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);
        }
      }
    

    要消除所有标记,您应该使用 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 = [];
      }
    

    这是我的完整代码 . 这是我可以减少的最简单的 . Be care full 您可以使用关键的Google 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>
    

    您也可以查阅google developer或完整文档,google developer web site .

  • 2

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

    两个答案中发布的“ set_map ”功能似乎在Google Maps v3 API中不再有效 .

    我不知道发生了什么

    Update:

    Google似乎改变了他们的API那个“ set_map " is not " setMap ” .

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

  • 15

    以下来自Anon的工作非常完美,但在重复清除叠加层时会出现闪烁现象 .

    只需执行以下操作:

    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:

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

    IV. Call the clearOverlays() function wherever required.

    而已!!

    希望能帮到你 .

  • 3

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

    1. Set up the MarkerManager

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

    2. Add markers to the 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

    mgr.clearMarkers();
    
  • 0

    在这里,您可以找到如何删除标记的示例:

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

    我刚刚尝试使用kmlLayer.setMap(null)并且它工作正常 . 不确定这是否适用于常规标记,但似乎可以正常工作 .

  • 0

    要清除所有叠加层,包括多边形,标记等...

    只需使用:

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

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

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

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

    1.addMarker(location):此函数用于在 Map 上添加标记

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

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

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

    查看Google示例以获取完整的代码示例:

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

  • -1

    我不知道为什么,但是,使用 DirectionsRenderersetMap(null) 设置为我的标记't work for me when I' m .

    在我的情况下,我不得不拨打 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);
        }
    });
    
  • 0

    只需遍历标记并从 Map 中删除它们,之后是空 Map 标记数组:

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

    只需清除Googlemap

    mGoogle_map.clear();
    
  • -2

    我使用了一个能很好地完成工作的速记 . 做就是了

    map.clear();
    
  • 0

    我已经尝试了所有提议的解决方案,但是当我的所有标记都在群集下时,没有任何对我有用 . 最后我只是说:

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

    最干净的方法是迭代 Map 的所有功能 . 标记(以及多边形,折线等)存储在 Map 的data layer中 .

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

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

    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类方法 .

  • 6

    你的意思是删除,如隐藏或删除它们?

    如果隐藏:

    function clearMarkers() {
                setAllMap(null);
            }
    

    如果你想删除它们:

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

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

  • 2

    您需要将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);
       }
    
  • -2

    如果您使用gmap V3插件: $("#map").gmap("removeAllMarkers");

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

  • 6

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

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

    每次都适合我 .

  • 0

    使用此功能,您可以从 Map 中删除所有标记 .

    map.clear();
    

    这会对你有所帮助,它对我有所帮助..

相关问题