Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create InfoWindows for Multiple Markers in a For loop

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?

like image 653
clifgray Avatar asked Sep 10 '12 15:09

clifgray


1 Answers

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.

like image 71
Marcelo Avatar answered Oct 01 '22 07:10

Marcelo