我用这段代码创建了一个谷歌地图:
function load() {
var markersArray = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("getMapMarkers.php", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var brewID = markers[i].getAttribute("brewID");
//construct url
var breweryLink = "http://beerportfolio.com/breweryPage.php?id=" + brewID;
//create directions link
http://maps.google.com/maps?daddr=
var directionsLink = "http://maps.google.com/maps?daddr=";
directionsLink = directionsLink + markers[i].getAttribute("lat") +"," + markers[i].getAttribute("lng")
var html = "<b><a href=\"" + breweryLink + "\">"+name+"</a> </b> <br/>" ;
html = html + "<br> <br>";
html = html + "<a href=\"" + directionsLink + " \">(Click for Directions)</a>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
bounds.extend(point);
}
map.fitBounds(bounds);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, 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 getMapVisit()
{
alert("clearing overlays...");
clearOverlays();
return false;
}
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function doNothing() {}
当我尝试删除标记以重新加载不同的标记时,我无法将它们从地图上删除。
按下按钮时,我调用getMapVisit()
然后调用clearOverlays()
,但clearOverlays()
不清除地图。在 Chrome 中,当我检查元素时,我收到此错误:
Uncaught ReferenceError: markersArray is not defined
该错误在第 86 行调用,即:
if (markersArray) {
我不知道为什么它在顶部明确初始化的数组时没有定义load()