On Jun 10, 3:02 pm, Seth <[email protected]> wrote:
> I think it might have something to do with the loop, but how do i
> solve that?
>
the loop looks something like:
-----------------------------
for (var i = 0; i < markers.length; i++) {
  directionsService.route(request, function(response, status) {
    var content = markers[i].getAttribute("name");
  });
}
-----------------------------
which means the loop will send a directions service request for all
markers before any response is received from google.  If there are 10
markers, there will be 10 almost simultaneous directions requests,
none of which has yet responded.

At the time when the first response is received, the loop variable "i"
will equal markers.length, and markers[markers.length] is undefined.

To fix this you need to get closure on a variable, so the inner
function can have access to it without it changing in the meantime.

You could try a loop that calls a function with a single marker:

-----------------------------
for (var i = 0; i < markers.length; i++) {
  getDirections(start, markers[i]);
}

function getDirections(start, marker) {

  var latlng = new google.maps.LatLng(
    parseFloat(marker.getAttribute("lat")),
    parseFloat(marker.getAttribute("lng")));

  var request = {
    origin : start,
    destination : latlng,
    travelMode : google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    var content = marker.getAttribute("name");
    // set up info window etc
  });
}
-----------------------------

-- 
You received this message because you are subscribed to the Google Groups 
"Google Maps JavaScript API v3" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-maps-js-api-v3?hl=en.

Reply via email to