I am using the Google Maps API to display a series of markers on a map. If there are no markers visible I want to display a little message advising the user to zoom out.
This is the code I am currently using:
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
}
});
Regardless of how many markers are visible, the value of "counter" is always zero.
I've read numerous similar questions on here and it appears to be something to do with global and local scope and/or "hoisting". Whatever I try I cannot get "counter" to give me the actual count of the markers. If I understand correctly, the "counter" inside the "for" loop is being treated as a different variable to the one defined in the "bounds changed" function. But I can't find any way of it all being treated as one variable.