Google Maps按钮嵌入Marker经纬度链接至index.php问题求助
Hey there! Let's sort out that button link issue with your Google Maps markers. I get that you want each marker's button to link to /index.php?newlat=xx.xxxx&newlng=xx.xxxx with the correct coordinates, but you're having trouble getting those values into the URL. Here's a straightforward solution and some tips to make it work:
Every Google Maps Marker object has a getPosition() method that returns a LatLng object. You can use this to pull the exact latitude and longitude values whenever you need them—this is the key to making your link dynamic.
Instead of hardcoding the button's href, generate it on the fly when you create the marker's info window. Here's a concrete example of how to implement this:
// Example marker creation (adjust to match your code structure) const marker = new google.maps.Marker({ position: { lat: YOUR_LAT_VALUE, lng: YOUR_LNG_VALUE }, // Replace with your actual coordinates map: yourMapInstance // Replace with your map variable name }); // Fetch the marker's coordinates const markerLat = marker.getPosition().lat(); const markerLng = marker.getPosition().lng(); // Create the info window content with the dynamic link const infoWindowContent = ` <button onclick="window.location.href='/index.php?newlat=${markerLat}&newlng=${markerLng}'"> Use This Coordinate </button> `; // Attach the info window to the marker const infoWindow = new google.maps.InfoWindow({ content: infoWindowContent }); marker.addListener('click', () => { infoWindow.open(yourMapInstance, marker); });
- Scoping issues in loops: If you're creating multiple markers in a loop, make sure you use
let/constfor your marker variable (instead ofvar) or wrap the marker creation in an IIFE. This ensures each button uses the correct marker's coordinates, not the last one in the loop. - Verify coordinate values: Add
console.log(markerLat, markerLng)right after fetching them to double-check that the numbers are being pulled correctly—this helps rule out issues with accessing the marker's position. - Avoid hardcoded placeholders: If you were using static text like
xx.xxxxbefore, replacing that with the dynamic${markerLat}and${markerLng}template literals will inject the real values.
By generating the button's URL when you create the marker, you're capturing the exact coordinates at the moment the marker is initialized. This avoids any issues with trying to access the marker's position later when the button is clicked (like if the marker reference is lost or scoped incorrectly).
内容的提问来源于stack exchange,提问作者Suchyman

