我正在使用 Google Maps API 在地图上显示一系列标记。如果没有可见的标记,我想显示一条小消息,建议用户缩小。
这是我当前使用的代码:
google.maps.event.addListener(map, 'bounds_changed', function() {
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
n = ne.lat();
e = ne.lng();
s = sw.lat();
w = sw.lng();
var counter = 0; // Define "counter" and set it to zero each time the bounds are changed
var xmlfile = 'php-to-xml-dev.php?n=' + n + "&e=" + e + "&s=" + s + "&w=" + w;
downloadUrl(xmlfile, function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var content=markers[i].getAttribute("content");
var icn=markers[i].getAttribute("icon");
createMarker(point, content, icn);
counter++; // Increment "counter" by 1
}
});
if (counter > 0) {
locationButton.classList.add("custom-map-control-hidden"); // Hide the message button
}else{
//locationButton.textContent = 'No defibs visible. Try zooming out.';
locationButton.textContent = counter; // Temporary line in place of the one above for debugging
}
});
无论有多少个标记可见,“计数器”的值始终为零。
我在这里阅读了许多类似的问题,它似乎与全局和局部范围和/或“提升”有关。无论我尝试什么,我都无法让“计数器”给我标记的实际计数。如果我理解正确,“for”循环内的“计数器”被视为与“边界更改”函数中定义的变量不同的变量。但我找不到任何方法将其全部视为一个变量。
请温柔地对待我。我对 Javascript 还是个新手。