簡體   English   中英

Google Maps API v3:如何刪除所有標記?

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

在 Google Maps API v2 中,如果我想刪除所有地圖標記,我可以簡單地執行以下操作:

map.clearOverlays();

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

查看Reference API ,我不清楚。

只需執行以下操作:

一、聲明一個全局變量:

var markersArray = [];

二、 定義一個函數:

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

三、 在調用以下命令之前,在“markerArray”中推送標記:

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

四、 調用clearOverlays(); map.clearOverlays(); 在任何需要的地方發揮作用。

而已!!

同樣的問題。 此代碼不再起作用。

我已經更正了,以這種方式更改 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

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

優點

  • 這樣做可以使代碼緊湊並集中在一個地方(不會污染命名空間)。
  • 您不必再自己跟蹤標記,您始終可以通過調用 map.getMarkers() 找到地圖上的所有標記

缺點

  • 像我現在一樣使用原型和包裝器使我的代碼依賴於 Google 代碼,如果他們對源代碼進行了重大更改,這將會中斷。
  • 如果你不理解它,那么你將無法修復它。 他們改變任何會破壞這一點的可能性很小,但仍然..
  • 如果您手動刪除一個標記,它的引用仍將在標記數組中。 (你可以編輯我的 setMap 方法來修復它,但代價是循環低谷標記數組並刪除引用)

這是YingYang 於 2014 年 3 月 11 日 15:049在對用戶原始問題的原始回復下最初發布的所有解決方案中最簡單的

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

我認為 V3 中沒有,所以我使用了上面的自定義實現。

免責聲明:這段代碼不是我寫的,但我在將它合並到我的代碼庫中時忘記保留引用,所以我不知道它來自哪里。

在新版本 v3 上,他們建議保留在數組中。 如下。

請參閱覆蓋概述中的示例。

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

只在 IE 上工作。


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

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

羅林格答案的簡潔應用。

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

解決方法很簡單。 您可以使用以下方法: marker.setMap(map); . 在這里,您定義圖釘將出現在哪個地圖上。

因此,如果您在此方法中設置nullmarker.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);
}

這是一個函數,可以設置或消失地圖中數組的所有標記:

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

您可以在google developer 網站上咨詢google developer或完整的文檔。

Google 的 Demo Gallery 有一個關於他們如何做的演示:

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

您可以查看源代碼以了解它們如何添加標記。

長話短說,他們將標記保存在全局數組中。 清除/刪除它們時,它們會遍歷數組並在給定的標記對象上調用“.setMap(null)”。

然而,這個例子展示了一個“技巧”。 本示例中的“清除”意味着將它們從地圖中刪除,但將它們保留在數組中,這允許應用程序快速將它們重新添加到地圖中。 從某種意義上說,這就像“隱藏”它們。

“刪除”也會清除數組。

兩個答案中發布的“ set_map ”函數似乎不再適用於 Google Maps v3 API。

我不知道發生了什么

更新:

谷歌似乎改變了他們的 API,使得“ set_map ”不是“ setMap ”。

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

您可以在此處找到有關如何刪除標記的示例:

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

以下來自 Anon 的作品完美無缺,盡管在反復清除疊加層時會閃爍。

只需執行以下操作:

一、聲明一個全局變量:

var markersArray = [];

二、 定義一個函數:

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

三、 在調用以下命令之前,在“markerArray”中推送標記:

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

四、 在需要的地方調用clearOverlays()函數。

而已!!

希望這會幫助你。

我發現在 google-maps-utility-library-v3 項目中使用 markermanager 庫是最簡單的方法。

1.設置MarkerManager

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

你也可以這樣做:

function clearMarkers(category){ 
  var i;       

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

清除所有疊加層,包括多邊形、標記等...

只需使用:

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

要從地圖中刪除所有標記,請創建如下函數:

1.addMarker(location):該函數用於在地圖上添加標記

2.clearMarkers():該函數從地圖中刪除所有標記,而不是從數組中刪除

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

最簡潔的方法是迭代地圖的所有特征。 標記(連同多邊形、折線等)存儲在地圖的數據層中。

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 類方法。

我剛剛用 kmlLayer.setMap(null) 試過這個,它奏效了。 不確定這是否適用於常規標記,但似乎可以正常工作。

這是 Google 自己在至少一個示例中使用的方法:

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

我不知道為什么,但是,當我使用DirectionsRenderer時,將setMap(null)設置為我的標記對我不起作用。

在我的情況下,我也必須將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);
    }
});

只需走過標記並將它們從地圖中刪除,然后清空地圖標記數組:

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

只需清除谷歌地圖

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

頂部投票最多的答案是正確的,但如果您一次只有一個標記(就像我的情況一樣)並且每次您需要殺死該標記的前一個位置並添加一個新位置,那么您就不需要需要創建整個標記數組並在每次推送和彈出時對其進行管理,您只需創建一個變量來存儲標記的先前位置,並可以在創建新標記時將其設置為 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;

你的意思是刪除隱藏它們或刪除它們?

如果隱藏:

function clearMarkers() {
            setAllMap(null);
        }

如果您想刪除它們:

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

請注意,我使用數組標記來跟蹤它們並手動重置它。

您需要將 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);
   }

我找到了簡單的解決方案(我認為):

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

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

我使用的速記可以很好地完成工作。 做就是了

    map.clear();

使用此功能,您可以從地圖中刪除所有標記。

map.clear();

這會對你有所幫助,它對我幫助..

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM