Search code examples
javascripteventsgoogle-maps-api-3infowindow

JavaScript google maps API - one one infowindow open at a time..


This questions relating to infowindow in the google maps API v3..

Currently I loop this function and place markers..

function addPostCode(zip, html) 
{
   geocoder.geocode( { 'address': zip}, function(results, status) 
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         map.setCenter(results[0].geometry.location);
         var marker = new google.maps.Marker({
         map: map,
         position: results[0].geometry.location,
         name: zip
      });
});

Now I would like to add an info windows with unique HTML, however I would like the following behaviour..

When an infowindow is opened by an event, any current infowindows will close leaving only the new one present..

Is this possible and how would I go about it? Finding documentation on this issue is proving difficult..


Solution

  • Create a single infowindow in your initialization. In your event/listener where you want to open the infowindow, you'd set the content and open the infowindow on the marker/location on the map.

    // Initialize infowindow
    var infowindow = new google.maps.InfoWindow({content: ''});
    
    function add_marker(point, name, content)
    {
       var marker = new google.maps.Marker({
          map: map,
          position: point,
          dragable: false,
          clickable: true,
          name: name
       });
       marker.content = content;
       google.maps.event.addListener(marker, 'click', function()
       {
          infowindow.content = marker.content;
          infowindow.open(map, marker);
       });
       return marker;
    };
    
    function addPostCode(zip, html) 
    {
       geocoder.geocode( { 'address': zip}, function(results, status) 
       {
          if (status == google.maps.GeocoderStatus.OK)
          {
             map.setCenter(results[0].geometry.location);
             var marker = add_marker(results[0].geometry.location, zip, html)
          });
    });
    

    This question and answer helped me out quite a bit with the single or multiple Info Window issue:

    Google Maps API v3 adding an InfoWindow to each marker