0

I am building a script which will get users locations using the Google Maps API. Once the data is retrieved I want to send them via a form in order to pass them to PHP. I read a little about it and found a jquery function that waits until the request is finished and then automatically submits the form. So I build this:

function writeAddressName(latLng, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
            "location": latLng
        },
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                document.getElementById("address").value = results[0].formatted_address;
                callback(results);
            } else {
                document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
                callback(null);
            }
        });
}

writeAddressName(userLatLng, function(results) {
    if (results) {
        $('#autoform').submit();
    } else {
        document.getElementById("error").innerHTML += "ERROR";
    }
});

This is the part of the code I modified to wait for the request to finish. The rest is a standard example from Google Maps API. In the current code above the script doesn't generate an error but also doesn't wait for the request to be finished.

Summary: I used the the callback function to make it wait for the request to finish. The script above is updated.

duncan
  • 31,401
  • 13
  • 78
  • 99
user1857756
  • 385
  • 3
  • 4
  • 14

0 Answers0