我试图删除地图上的所有标记。
我试图使用:
marker.setMap(null)
但它只删除了一个标记。
如何删除地图上的所有标记?
答案 0 :(得分:2)
问题是您的标记变量仅存储最后一个标记。
您必须将所有标记推入数组。使用此数组,您将能够从地图中删除每个标记。看一下代码中的注释。 ;)
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
var map;
var markers;
var point;
var xml;
var markerArr = []; // NEW ARRAY
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 12
});
}
function drop() {
var infoWindow = new google.maps.InfoWindow;
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
marker = new google.maps.Marker({
map: map,
position: point,
animation: google.maps.Animation.DROP
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
markerArr.push(marker); // PUSH EACH MARKER INTO AN ARRAY
});
});
}
function clearMarkers() {
for (var i = 0; i < markerArr.length; i++) {
markerArr[i].setMap(null); // REMOVE EACH MARKER
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
&#13;
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
&#13;
<div id="floating-panel">
<button id="drop" onclick="drop()">Drop Markers</button>
<button id="clearMarkers" onclick="clearMarkers()">clear Markers</button>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
&#13;