[javascript] Google Map API v3 ~ Simply Close an infowindow?

Trying to simply close an infowindow?

I already have an array of markers, so something like this would be good. Thanks

MyMarkers[i].infowindow.close();

This question is related to javascript google-maps google-maps-api-3

The answer is


We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();


infowindow.open(null,null);

will close opened infowindow. It will work same as


You could simply add a click listener on the map inside the function that creates the InfoWindow

google.maps.event.addListener(marker, 'click', function() {
    var infoWindow = createInfoWindowForMarker(marker);
    infoWindow.open(map, marker);
    google.maps.event.addListener(map, 'click', function() {
        infoWindow.close();
    });
});

The following event listener solved this nicely for me even when using multiple markers and info windows:

//Add click event listener
google.maps.event.addListener(marker, 'click', function() {
  // Helper to check if the info window is already open
  google.maps.InfoWindow.prototype.isOpen = function(){
      var map = infoWindow.getMap();
      return (map !== null && typeof map !== "undefined");
  }
  // Do the check
  if (infoWindow.isOpen()){
    // Close the info window
    infoWindow.close();
  } else {
    //Set the new content
    infoWindow.setContent(contentString);
    //Open the infowindow
    infoWindow.open(map, marker);
  }
});

This one would also work:

google.maps.event.addListener(marker, 'click', function() {
                if(!marker.open){
                    infowindow.open(map,marker);
                    marker.open = true;
                }
                else{
                    infowindow.close();
                    marker.open = false;
                }
            });

Which will open an infoWindow when clicked on it, close it when clicked on it if it was opened.

Also having seen Logan's solution, these 2 can be combined into this:

google.maps.event.addListener(marker, 'click', function() {
                if(!marker.open){
                    infowindow.open(map,marker);
                    marker.open = true;
                }
                else{
                    infowindow.close();
                    marker.open = false;
                }
                google.maps.event.addListener(map, 'click', function() {
                    infowindow.close();
                    marker.open = false;
                });
            });

Which will open an infoWindow when clicked on it, close it when clicked on it and it was opened, and close it if it's clicked anywhere on the map and the infoWindows was opened.


Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

I was having a similar issue. I simply added the following to my code:

closeInfoWindow = function() {
    infoWindow.close();
};

google.maps.event.addListener(map, 'click', closeInfoWindow);

The full js code is (the code above is about 15 lines from the bottom):

jQuery(window).load(function() {
if (jQuery("#map_canvas").length > 0){
    googlemap();
}
});

function googlemap() {

jQuery('#map_canvas').css({'height': '400px'});

// Create the map 
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  streetViewControl: false
});

// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");

var myOptions = {
         content: boxText
        ,disableAutoPan: false
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-117,-200)
        ,zIndex: null
        ,boxStyle: { 
          background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
          ,opacity: 1
          ,width: "236px"
          ,height: "300px"
         }
        ,closeBoxMargin: "10px 0px 2px 2px"
        ,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.gif"
        ,infoBoxClearance: new google.maps.Size(1, 1)
        ,isHidden: false
        ,pane: "floatPane"
        ,enableEventPropagation: false
};


var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';

// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        title: data.title,
        content: data.html,
        icon: MarkerImage
    });
    google.maps.event.addListener(marker, "click", function() {
        infoWindow.open(map, this);         
        title.innerHTML = marker.getTitle();
        infoWindow.setContent(marker.content);
        infoWindow.open(map, marker);
        jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});            
    });
}

// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
    var data = markers[index];
    bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.

closeInfoWindow = function() {
        infoWindow.close();
    };

google.maps.event.addListener(map, 'click', closeInfoWindow);

google.maps.event.addListener(infoWindow, 'closeclick', function()
{
    centermap();
});

function centermap()
{
    map.setCenter(map.fitBounds(bounds));
}
}

jQuery(window).resize(function() {
googlemap();
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-api-3

Google Maps shows "For development purposes only" Googlemaps API Key for Localhost ERROR: Google Maps API error: MissingKeyMapError Google Maps API warning: NoApiKeys Google Maps JavaScript API RefererNotAllowedMapError This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console TypeError: window.initMap is not a function Google maps Marker Label with multiple characters Google Maps how to Show city or an Area outline How to use SVG markers in Google Maps API v3