Solved

Javascript Callback or counter

Posted on 2014-04-08
3
384 Views
Last Modified: 2014-05-29
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
Comment
Question by:lvmllc
3 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39987189
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
 

Author Comment

by:lvmllc
ID: 39987409
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
 
LVL 49

Accepted Solution

by:
Roonaan earned 500 total points
ID: 40056953
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now