Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google map (v3) infowindow opening on the same marker all the time

I create several Gmarkers (from JSON data loaded by JQuery "load" function), on all of them I add an event listener to open the infowindow object I created before on the marker, and then I add them all to the map.

The issue is that the infowindow always opens on the same marker. I all had this working before, i can't see where the problem is... scope of the variable ? stupid mistake somewhere ?

I uploaded an example, and here is a shortcut to the javascript file

The code :

    var map;
    var infowindow;
    $(document).ready(function() {

        var myLatlng = new google.maps.LatLng(47.15984,2.329102);
      var myOptions = {
        zoom: 6,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        scrollwheel: false
      }

      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

      infowindow = new google.maps.InfoWindow({content:'<p>Test</p>'});

        $.getJSON("data.json", function(data) {

            var markers = [];
            for (var i = data.length - 1; i >= 0; i--){
                var latLng = new google.maps.LatLng(data[i].lat, data[i].lng);
              var marker = new google.maps.Marker({position: latLng});

              google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
              });

              markers.push(marker);
            };

            for (var j = markers.length - 1; j >= 0; j--){
                markers[j].setMap(map);
            };

        });
    });
like image 933
Julien Avatar asked Oct 24 '10 22:10

Julien


People also ask

How do I get rid of InfoWindow in Google Maps?

After constructing an InfoWindow, you must call open to display it on the map. The user can click the close button on the InfoWindow to remove it from the map, or the developer can call close() for the same effect.

How do I edit InfoWindow on Google Maps?

You can modify the whole InfoWindow using jquery alone... var popup = new google. maps. InfoWindow({ content:'<p id="hook">Hello World!

How do I put InfoWindow on marker?

Call setPosition() on the info window, or. Attach the info window to a new marker using the InfoWindow. open() method. Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.


1 Answers

Change

infowindow.open(map,marker);

to

infowindow.open(map,this);
like image 53
cambraca Avatar answered Sep 28 '22 06:09

cambraca