Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 396
  • Last Modified:

Javascript Callback or counter

I have a working Google API geocoder that looks up the name of a county that a city is in and then puts the resulting list of counties into a new array.
However when testing I see that sometimes the order in which the counties are returned is different. I suspect what is happening is that all of the requests are being sent one right after the other but the API has different servers processing so sometimes the first city sent is the last one returned.  - is there a way to make this sequential? - this is a minor issue as I could just rebuild the address array in the order of returned values - just curous as to why it does what it does now.

The other issue i have is that if I have a long list of addresses the script moves ahead to my do something new part of the code before it finishes getting all of the address.

Do I need a callback or some type of counter to ensure that it gets all the responses before moving ahead?



<div id='myInfo1'>-</div>
<div id='myInfo2'>-</div>

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry) {
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties.push(county);

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });

});

//now do something with those results after all are received.

Open in new window

0
lvmllc
Asked:
lvmllc
1 Solution
 
Chris StanyonCommented:
The reason they may come back out of sequence is simply down to the nature of AJAX calls. You make an AJAX call for each address in your list, but because the AJAX call is asynchronous, it doesn't wait around to finish before starting the next one. It may just be that the request for the first address takes slightly longer at the server than the request for the second request.

As for your code continuing to run - exactly the same reason as above - you make your calls Asynchronously, so your code doesn't stop and wait for the responses - it just carries on.

Normally, if you want to run code after the AJAX has finished, you make use of the 'Success' argument or .done() method

If you absolutely need your data returned 'in order' and only continue on with your code after all requests have finished, then you may have to change your AJAX request to a Synchronous one - the downside being it locks the browser while it's working.

As far as I'm aware there isn't a native callback mechanism for Google Geocoding
0
 
lvmllcAuthor Commented:
Chris - let me try something with the .done() method - I'll post back tomorrow on what I figure out along with any question I might still have for you.
0
 
RoonaanCommented:
The forEach method actually provides a second argument, which is the original index in the array.

Using that, you could insert the response in the same index as the addresses:

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry, index) {
        //                             ^---- Use index argument from original array
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties[index] = county; //  INSERT AT ASSOCIATED INDEX

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });
});

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now