Google Maps为Marker添加InfoWindow:门店定位器代码功能扩展问询
Got it, let's get that InfoWindow working for your markers. Here's a straightforward, efficient way to modify your existing code to add interactive info windows when users click on store markers:
Step 1: Create a Reusable InfoWindow Instance
First, create a single InfoWindow outside your generateMarkers function—this lets us reuse the same window for all markers instead of creating a new one each time, which is better for performance:
// Initialize one shared InfoWindow to use across all markers const storeInfoWindow = new google.maps.InfoWindow();
Step 2: Update Your Marker Generation Code
Modify your generateMarkers function to add a click event listener to each marker, which triggers the InfoWindow to open with your store details:
function generateMarkers(points) { // var iconBase = "https://media.nisbets.com/static/content/banners/"; for (var i = 0; i < points.length; i++) { var place = points[i]; var myLatLng = new google.maps.LatLng(place[0], place[1]); var marker = new google.maps.Marker({ position: myLatLng, name: place[2], clickable: true, map: map, icon: /*iconBase + */"nisbets_storelocator_marker.png", url: place[3] // Add any other store properties you want to display here, e.g., address: place[4] }); // Add click event to open InfoWindow google.maps.event.addListener(marker, 'click', function() { // Customize this HTML content to match your store's data const infoContent = ` <div style="padding: 10px;"> <h4 style="margin: 0 0 8px;">${this.name}</h4> <p style="margin: 0 0 6px;"> <a href="${this.url}" target="_blank" rel="noopener">Visit Store Page</a> </p> <!-- Add more fields here if you have them, like address, phone, etc. --> <!-- Example: <p>Address: ${this.address}</p> --> </div> `; // Update the InfoWindow content and open it on the clicked marker storeInfoWindow.setContent(infoContent); storeInfoWindow.open(map, this); }); } }
Step 3: Optional - Add Map Click to Close InfoWindow
If you want the InfoWindow to close when users click anywhere else on the map, add this listener outside your function:
// Close InfoWindow when clicking the map background google.maps.event.addListener(map, 'click', () => { storeInfoWindow.close(); });
Key Notes:
- Reusable InfoWindow: Using one instance instead of multiple prevents clutter and improves performance, especially if you have many store markers.
- Customizable Content: The HTML inside
infoContentis fully flexible—you can add store addresses, phone numbers, hours, or even images as long as you include that data in yourpointsarray (just add properties to the Marker object, likeaddress: place[4], then referencethis.addressin the content). thisKeyword: In the click event callback,thisrefers to the marker that was clicked, so you can access all its properties directly.
内容的提问来源于stack exchange,提问作者Happi Olivier

