Google Maps - Info Window
Google Maps - Using Info Windows
Section titled “Google Maps - Using Info Windows”An InfoWindow displays content (usually text or images) in a pop-up window above the map, typically anchored to a specific location or marker. They are commonly used to provide details about a point of interest when a user interacts with it (e.g., clicks a marker).
Creating an InfoWindow
Section titled “Creating an InfoWindow”You create an InfoWindow by instantiating the google.maps.InfoWindow class. Its constructor takes an InfoWindowOptions object.
Key InfoWindow Options:
Section titled “Key InfoWindow Options:”content: The content to display. This can be an HTML string (e.g.,'<h3>Title</h3><p>Details...</p>') or a DOM Node.position: ALatLngobject or literal ({lat: ..., lng: ...}) specifying the location where the InfoWindow should be anchored if not attached to a marker.pixelOffset: Agoogle.maps.Sizeobject specifying the offset (in pixels) from the InfoWindow’s anchor point to where it should appear.maxWidth: The maximum width of the InfoWindow in pixels. Content will wrap if it exceeds this width.ariaLabel: Provides a text label for screen readers, improving accessibility, especially when the content is complex or image-based.
Example: Creating a Simple InfoWindow
Section titled “Example: Creating a Simple InfoWindow”// Ensure InfoWindow is imported: const { InfoWindow } = await google.maps.importLibrary("maps");
const infoContent = ` <div style="font-family: sans-serif;"> <h4>Jubilee Hills, Hyderabad</h4> <p>A prominent residential and commercial area.</p> <a href="#" target="_blank">More info...</a> </div>`;
const infowindow = new google.maps.InfoWindow({ content: infoContent, maxWidth: 250, // Limit width ariaLabel: 'Jubilee Hills Information'});Opening an InfoWindow
Section titled “Opening an InfoWindow”Creating an InfoWindow doesn’t automatically display it. You need to call its open() method.
Modern Syntax (Recommended):
Section titled “Modern Syntax (Recommended):”The preferred open method takes a single object argument:
infowindow.open({ map: map, // The map instance to display on anchor: marker, // Optional: The marker to anchor to // position: latLng // Optional: Use if not anchoring to a marker shouldFocus: false // Optional: Prevents map panning to fit window if true});Using anchor is generally preferred when associating with a marker, as it handles positioning automatically, even if the marker icon changes.
Legacy Syntax:
Section titled “Legacy Syntax:”The older syntax infowindow.open(map, marker); still works but is less flexible.
Common Use Case: Open on Marker Click
Section titled “Common Use Case: Open on Marker Click”This combines creating a marker, creating an InfoWindow, and adding a click listener to the marker to open the window.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>InfoWindow on Marker Click</title> <style>#map { height: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; }</style></head><body> <div id="map"></div> <script> let currentInfoWindow = null; // Track the currently open InfoWindow
async function initMap() { const mapCenter = { lat: 17.4330, lng: 78.4121 }; // Jubilee Hills area const { Map, InfoWindow } = await google.maps.importLibrary("maps"); const { Marker } = await google.maps.importLibrary("marker");
const map = new Map(document.getElementById("map"), { zoom: 14, center: mapCenter, mapId: "DEMO_MAP_ID" });
// Create the marker const marker = new Marker({ position: mapCenter, map: map, title: 'Jubilee Hills', // Optional: Use a custom icon // icon: 'https://maps.google.com/mapfiles/ms/icons/red-dot.png' });
// Create the InfoWindow (can be reused or created per marker) const infoContent = ` <div> **Jubilee Hills**<br> Hyderabad, Telangana<br> INDIA-500033 </div>`; const infowindow = new InfoWindow({ content: infoContent, maxWidth: 200, ariaLabel: 'Jubilee Hills Location' });
// Add click listener to the marker marker.addListener('click', () => { // Close the previously opened info window (if any) if (currentInfoWindow) { currentInfoWindow.close(); } // Open the new one infowindow.open({ anchor: marker, map }); currentInfoWindow = infowindow; // Track the current window });
// Close info window if map is clicked map.addListener('click', () => { if (currentInfoWindow) { currentInfoWindow.close(); currentInfoWindow = null; } }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker,maps" async defer></script></body></html>Expected Output: A map centered near Jubilee Hills, Hyderabad, with a marker. Clicking the marker opens an InfoWindow displaying the address details. Clicking elsewhere on the map closes the InfoWindow.
Closing an InfoWindow
Section titled “Closing an InfoWindow”You can programmatically close an InfoWindow using its close() method.
infowindow.close();It’s good practice to close any currently open InfoWindow before opening a new one, especially if you have multiple markers, to avoid clutter.
InfoWindow Events
Section titled “InfoWindow Events”InfoWindows also emit events:
closeclick: Fired when the user clicks the close button (the ‘x’ in the top-right corner).content_changed: Fired when thecontentproperty changes.domready: Fired when the InfoWindow’s content (DOM structure) is ready to be interacted with (useful if your content includes elements that need event listeners attached).
Example: Listening for Close Click
Section titled “Example: Listening for Close Click”infowindow.addListener('closeclick', () => { console.log('InfoWindow closed by user.'); // Perform cleanup or update state if needed currentInfoWindow = null; // Update tracking variable});