Note that there are some explanatory texts on larger screens.

plurals
  1. POGoogle Maps Trouble: Closures & Passing By Reference
    text
    copied!<p>I'm having some Google Maps/Javascript problems. I think I know what the trouble is but just don't know a way round it.</p> <p>An example of my problem is <a href="http://www.ltheobald.co.uk/maptest/test.html" rel="noreferrer">here</a>. Whatever marker you click on, the second shows up. I'm obviously passing the wrong info into my event listener but I just can't seem to get the code right. Here's a cut down portion of the code:</p> <p>First, here's a portion of my code:</p> <pre><code>if (GBrowserIsCompatible() &amp;&amp; mapResults != null) { // Read in the JSON var mapDetailsArray = loadJSON(); // Create a map var map = new google.maps.Map2(document.getElementById(elementId)); map.setCenter(new google.maps.LatLng(mapDetailsArray[0].getLatitude(), mapDetailsArray[0].getLongitude()), 13); map.addControl(new google.maps.SmallMapControl()); // Add the points and center var mgr = new google.maps.MarkerManager(map); var bounds = new google.maps.LatLngBounds(); for ( var i = 0; i &lt; mapDetailsArray.length; i++) { var mapDetails = mapDetailsArray[i]; var point = new google.maps.LatLng(mapDetails.getLatitude(), mapDetails .getLongitude()); bounds.extend(point); // Create our marker var marker = new google.maps.Marker(point); // What action do we use to show the hover var infoAction = "mouseover"; marker.value = mapDetails; google.maps.Event.addListener(marker, infoAction, function() { alert(marker.value); map.openInfoWindowHtml(point, getResultInfoContent(marker.value)); }); mgr.addMarker(marker, 1); } mgr.refresh(); } </code></pre> <p>"marker.value" always ends up set as the last value of what mapDetails was. If anything, I'd expect it to be "undefined" as once the loop has finished, shouldn't that value be gone anyway? I've tried various different values (e.g. marker.value = i+1;) but it will still come up as the same value for both points.</p> <p>Does anyone have any idea how I can pass the correct values into the event listener?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload