0

im using the Google API, i want to make it that there can be multiple addresses marked on the map so im using the Geocoder. However the rest of my code is running before this Geocoder returns the result it seems!

// Handle addresses
var addressesHandled = [];
function handleAddresses(addressObj) {
    for (i = 0; i < addressObj.length; i++) {
        addressesHandled[i] = new Address(addressObj[i]['title'], addressObj[i]['address'], addressObj[i]['latlng'], addressObj[i]['defaultOpen']);
    }
}
// Address object
function Address(title, address, latlng, defaultOpen) {
    this.title = title;
    this.address = address;

    this.latlng = latlng;
    if (latlng == undefined) {
        this.latlng = codeAddress(address);
    }

    this.defaultOpen = defaultOpen;
}

As you can see im going through each object and getting the address if the lat and lng values are undefined. If these are undefined I then execute the codeAddress function which will get the lat and lng values from the current address, however I think that the rest of the script is still running whilst this happens!

Below is the codeAddress function, I thought I was unable to the return the result however now I believe that it simply isn't being returns quick enough.

How can I fix this issue so the rest of my script waits until each address has had it's lat and lng calculated!?

function codeAddress(address, callback) {
    var geocoder;
    geocoder = new google.maps.Geocoder();

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var loc = [];
            // loc = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
            loc[0] = results[0].geometry.location.lat(); loc[1] = results[0].geometry.location.lng();
            console.log(loc);

            callback(loc);
        } else {
            console.log("Geocode was not successful for the following reason: " + status);
        }
    });
}

Edit: Hmm, I just thought would it be easier just to process the marker and add it to the map as each geocode function has it's result returned ?

Martyn Ball
  • 3,848
  • 6
  • 38
  • 100
  • 1
    http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – mplungjan Jul 05 '16 at 15:30
  • 1
    Have a look at [Is it bad practice to have a constructor function return a Promise?](http://stackoverflow.com/q/24398699/1048572) So make `codeAddress` return a promise for an `Address`, not the other way round – Bergi Jul 05 '16 at 15:34

0 Answers0