Search code examples
javascriptgoogle-mapsgoogle-geocoder

store responses of an async method in the same order they are asked


I need to store some google maps coordinates in an array, I obtain the coordinates through the geocoder so I pass the name of the city or the address and it returns me the coordinates.

I found that geocoder must be an async function, because is not giving me the answers in the same order I ask them. So the coordinates are stored in a diferent order that I need.

For example, if I ask for barcelona -> paris -> barcelona the answer is always the coordinates of barcelona -> barcelona -> paris or paris -> barcelona -> barcelona. or if I ask paris -> roma -> oslo it answers in another order.

var address = ['Barcelona', 'Viena','Oslo'];
for (var i = 0; i < address.length; i++ ) {
   geocoder.geocode({
       'address': address[i]
   }, function (results, status) {

       if (status === google.maps.GeocoderStatus.OK) {
           lineCoordinates.push(results[0].geometry.location);
           cities.push(results[0].address_components[0].long_name);
           console.log("he terminado para:" + results[0].address_components[0].long_name);
       }
   });
}

how can I do to store the responses in the correct order?

thank you


Solution

  • You could work with callbacks for your purpose. Make your geocoding request to a function like:

    doGeocode: function (address, postal_code, callback) {
    console.log("TEST: " + address.toString());
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address,
        'componentRestrictions': {
            'postalCode': postal_code,
            'country': 'de'
        }
    }, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            console.log(results);
            callback(results);
        } else {
            //Error handling
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
    

    Now you could work within each callback like:

    doGeocode (adress, postal_code, function (response1){
    //Barcelona
      doGeocode (adress, postal_code, function (response2){
      //Viena
    
       doGeocode (adress, postal_code, function (response3){
          //Oslo
    
    
          //here you have all your requested information from all 3 requests
         )};
      )}; 
    )};