GetDistanceMatrix with Reference to External Variable

284 views
Skip to first unread message

Yau-Hsien Huang (黃耀賢)

unread,
Nov 21, 2011, 9:20:59 PM11/21/11
to google-map...@googlegroups.com
Hi, all. I have code about DistanceMatrixService.getDistanceMatrix function using
a external variable, listed as below:

        // To call find_links, use:
        //              find_links(new Array()
        //                            , [(25.0, 124.0)]
        //                            , [[(25.1, 124.1), (25.2, 124.2), ... ], [(26.1, 124.1), ... ]]);
        // The dest_group is an array of array of points; within it, the length of an array of points
        // would never exceed 25, the limit given by Google.

        function find_links(links, origin, dest_group) {
            var ll_o;
            var ll_d;
            var i;
            var destinations;
            for (i=0; i<dg.length; i++) {
                destinations = dest_group[i];
                ll_o = latLng([origin]);
                ll_d = latLng(destinations);
                measureDistance.getDistanceMatrix(
                    {
                        origins: ll_o,
                        destinations: ll_d,
                        travelMode: google.maps.TravelMode.DRIVING,
                        unitSystem: google.maps.UnitSystem.METRIC,
                        avoidHighways: false,
                        avoidTolls: false
                    }
                    , function(response, status){ approach_links(links, origin, destinations, response, status); }
                );
            }
        }

        function approach_links(links, origin, destinations, response, status) {
            alert(destinations);
            // , etc.
        }

The problem is that when in approach_links it alerts, the variable `destinations' always bound to
the last state of the variable `destinations' outer of measureDistance.getDistanceMatrix call in find_links.
That is, it seems like variable used in callback closure refers to a static external variable, doesn't it?
Any idea?

Rossko

unread,
Nov 22, 2011, 4:26:36 AM11/22/11
to Google Maps JavaScript API v3
> The problem is that when in approach_links it alerts, the variable
> `destinations' always bound to
> the last state of the variable `destinations' outer
> of measureDistance.getDistanceMatrix call in find_links.

Yes, your tight loop fires off several requests to Google, then the
loop finishes with 'destinations' holding the last value.
Some time later, the responses come back, and you alert that value.
You haven't got closure on 'destinations'

Don't use tight loops with asynchronous rate-limited functions, you
will get an error.

Reply all
Reply to author
Forward
0 new messages