As I work on dynamically adding info windows to Google Maps markers from a JSON array received from the server, I find myself grappling with Javascript's handling of variables and scope.
One attempt involved this code snippet:
$.getJSON("server", function(data) {
if (data.items.length > 0 {
var infowindow = new google.maps.InfoWindow({
content: "placeholder"
});
for (var i = 0; i < data.items.length; i++) {
var latLng = new google.maps.LatLng(data.items[i]["lat"],
data.items[i]["lng"]);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.items[i]["text"],
icon: data.items[i]["alert_type"],
animation: google.maps.Animation.DROP
});
marker.addListener('click', function() {
infowindow.setContent(data.items[i]["text"]);
infowindow.open(map, this);
});
} // end for
} // end if
}); // end getJSON
This code runs into an issue where clicking a marker triggers an error stating data.items[i] is undefined
. Despite being defined earlier in the code, multiple attempts to access it within the function have failed.
To circumvent the problem, I initialized a variable just before the function declaration:
var reportText = data.items[i]["text"];
. Subsequently, altering the problematic line to infowindow.setContent(reportText);
resolved the errors. However, all markers displayed the same text upon click, reflecting the last retrieved report instead of individualized information. Presumably, the infowindow retained the variable location rather than the string value when set, resulting in this behavior.
In another iteration, I modified my approach to initialize the marker differently:
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.items[i]["text"],
icon: data.items[i]["alert_type"],
label: reportText,
animation: google.maps.Animation.DROP
});
By assigning the label property accordingly, I could utilize:
infowindow.setContent(this.label);
This adjustment successfully displayed the correct text for each marker in the info window. However, the method proved incompatible with custom icons meant to accommodate labels, which resulted in less aesthetic marker appearances.
My goal now is to either conceal the label property while retaining its functionality, or ideally, modify setContent
to capture the string value at the time of execution instead of creating a reference point to a variable.
Any guidance on this matter would be greatly appreciated. Thank you.