Saturday, March 10, 2012

Revisiting a single InfoWindow setup


Instead of keeping track of several InfoWindows, we can store the information with each marker and use only one global InfoWindow.



Global variables:

      var infowindow;
      var count = 0;

Event listener and InfoWindow creation:

      function initialize() {
        map = new google.maps.Map($("map_canvas"), mapOptions);
        google.maps.event.addListener(map, 'click', function (event) {
          addMarker(event.latLng, "InfoWindow index #" + count);
          count += 1;
        });


        infowindow = new google.maps.InfoWindow({ });
      }

Defining a marker:


      function addMarker(pos, content) {
        var marker = new google.maps.Marker({
          map: map,
          position: pos
        });


When clicked, the marker opens the InfoWindow with the current content.


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


Full source code:

No comments:

Post a Comment