0

I have some issue with the callback inside geocoder.geocode.

var tri = new Array();
for (var j = 1; j < taille; j++) {
    where = getBoutique[j].adresse + ", " + getBoutique[j].ville;
    boutiqueProche(lat, lon, where, function (distanceO) {
        //window.localStorage.setItem("distance", distance);
        console.log(distanceO);
        tri.push(distanceO);
        //return distance;
        //console.log("Nous somme dans "+localStorage.getItem("distance"));
    });
    console.log("Inside " + tri);
}

function boutiqueProche(cLat, cLong, where, callback) {
    var geocoder = new google.maps.Geocoder();
    var currentPosition = new google.maps.LatLng(cLat, cLong); // On récupère nos info
    var recup = getBoutique.length;
    var distance;
    geocoder.geocode({
        'address': where
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var laBoutique = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
            distance = google.maps.geometry.spherical.computeDistanceBetween(currentPosition, laBoutique);
            recup = distance / 1000;
            callback(recup);
        } else {
            if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                setTimeout(function () {
                    boutiqueProche(cLat, cLong, where, callback); // rappel fonction avec meme param
                }, 200);
            } else { /*Faire quelque chose */ }
        }
    });
}

I want to fill the array tri with the data from recup variable. But when I fill tri, nothing happens. It is empty.

What is the problem?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • You are calling `console.log("Inside " + tri);` outside of the callback, i.e. before any element was added to the array. Making the geocoding request takes time and the `for` loop most likely finished before the first response was even received. Have a look at [this question](http://stackoverflow.com/q/14220321/218196) to get an idea about the differences between synchronous and asynchronous code. – Felix Kling Aug 04 '13 at 19:55
  • I read everything, understand the main problem but i don't know how to solve it... – user2651099 Aug 04 '13 at 20:25
  • You have to keep track of each call you make to `boutiqueProche` and execute a function once *all* responses have been received. The cleanest way to do this would be to use promises, such as implemented by when.js: https://github.com/cujojs/when. – Felix Kling Aug 04 '13 at 20:34
  • where should i put promise().done(); – user2651099 Aug 04 '13 at 21:06

0 Answers0