Google Maps标记点击无法唤起InfoWindow的技术问询
Hey there, let's break down why your markers stopped opening InfoWindows suddenly—even without code changes, Google Maps API updates can throw unexpected curveballs. Here are the most likely fixes and checks:
1. Fix the Critical Typo in Event Listener
First thing I spotted: your code uses google.map.event.addListener instead of google.maps.event.addListener (missing an s in maps). Older API versions might have tolerated this typo, but recent updates enforce stricter namespace checks, which would completely break the click event binding.
This is almost certainly the root cause. Correct that line, and your click handlers should start working again immediately.
2. Ensure Proper Initialization with the Callback
When you switched to the async defer script with callback=initMap, make sure all your map-related code lives inside the initMap function. If any code runs before the API finishes loading, markers might get created without proper event bindings.
Here's the corrected, properly structured code (I also cleaned up minor syntax issues):
function initMap() { var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); for (let i = 0; i < markers.length; i++) { // Use let to avoid loop variable scoping bugs var data = markers[i]; var myLatlng = new google.maps.LatLng(data.lat, data.lng); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: "Permit# " + data.permit, icon: `GoogleMapsMarkers/${data.icon}.png` // Cleaner template literal syntax }); // Preserve marker/data scope with an IIFE (your original approach is solid) (function (marker, data) { google.maps.event.addListener(marker, "click", function () { // Fixed stray " in the href to avoid HTML parsing issues infoWindow.setContent(` <b>${data.loc} ${data.type}</b> <br/> <a target="_blank" href="ViewPermit.aspx?PermNum=${data.permit}"> Open Permit #${data.permit} </a> `); infoWindow.open(map, marker); }); })(marker, data); } }
Keep your API script tag correctly configured for the callback:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=My_Key&callback=initMap"></script>
3. Check for Other Potential Issues
- Browser Console Errors: Hit F12 to open DevTools and check the Console tab for uncaught errors (e.g.,
markersarray being undefined, icon paths failing to load). - Overlaying Elements: Make sure no other page elements (like a hidden div, modal backdrop, or high-z-index component) are covering the map markers. Use DevTools' element picker to see what element actually receives the click when you tap a marker.
- API Version Locking: If the issue persists, try locking the API to a specific stable version (e.g.,
v=3.54) to rule out automatic updates causing conflicts:<script async defer src="https://maps.googleapis.com/maps/api/js?v=3.54&key=My_Key&callback=initMap"></script>
内容的提问来源于stack exchange,提问作者Dr.Prog

