I have the following code and it correctly creates all the markers that I am storing but then when I click on any of them only the last InfoWindow is created and it only appears over the last marker no matter which marker I click on. I would imagine this has something to so with the same variable being used in my for loop.
{% for record in records %}
//need to do the JSON encoding because JavaScript can't have Jinja2 variables
//I need the safe here because Jinja2 tries to escape the characters otherwise
var GPSlocation = {{record.GPSlocation|json_encode|safe}};
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);
var markerLatlng = new google.maps.LatLng(Lat, Lng);
var marker = new google.maps.Marker({
position: markerLatlng,
title: {{record.title|json_encode|safe}}
});
var infowindow = new google.maps.InfoWindow({
content: "holding..."
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent({{record.description|json_encode|safe}});
infowindow.open(map, marker);
});
//add the marker to the map
marker.setMap(map);
{% endfor %}
I tried changing the event listener to this:
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent({{record.description|json_encode|safe}});
infowindow.open(map, this);
});
As I saw that worked for some other users on SO but then no InfoWindows show up. Are there any obvious errors here?
You need to create the markers in a separate function:
// Global var
var infowindow = new google.maps.InfoWindow();
and then, inside the loop:
var markerLatlng = new google.maps.LatLng(Lat, Lng);
var title = {{record.title|json_encode|safe}}
var iwContent = {{record.description|json_encode|safe}}
createMarker(markerLatlng ,title,iwContent);
Finally:
function createMarker(latlon,title,iwContent) {
var marker = new google.maps.Marker({
position: latlon,
title: title,
map: map
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(iwContent);
infowindow.open(map, marker);
});
}
Explanation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With