0

On my page I'm using MaxMind to populate a users long/lat.

I'm also using a script (containing the haversine formula) to take the users long/lat and assign a distance parameter to an object that relates to a store location.

Once the distance has been stored I want to run the following loop

for(i=0; i<cities.length; i++){
    var newLat = cities[i].lat;
    var newLon = cities[i].lon;
    getDistanceFromLatLonInKm(userLat,userLon,newLat,newLon);
    var lowest = 1000
    if(cities[i].distance< lowest){lowest = cities[i].distance}
}

    cities.sort(function(a, b) {
    return a.distance - b.distance;
    })[0]
        var div = document.getElementById('test');
            if(cities[0].fax == null){
                div.innerHTML = div.innerHTML + cities[0].street + '<br />' + cities[0].city + '<br />' + cities[0].postal + '<br /><b>Phone:</b>' + cities[0].phone;
            }else{div.innerHTML = div.innerHTML + cities[0].street + '<br />' + cities[0].city + '<br />' + cities[0].postal + '<br /><b>Phone:</b>' + cities[0].phone + '<br /><b>Fax:</b>' + cities[0].fax;

            }

The only thing is that since there's a delay on the coordinates showing up, the loop can't run right away. How can I run this loop after the coordinates are populated?

1
  • Can you share the code which is getting the latitude and longitude? You can have a construct where you wrap the for loop inside the functionality of getting the latitude.. by saying something like if lat and long = actual values, { for loop } Commented Dec 9, 2013 at 19:02

1 Answer 1

1

You can use the setTimeout function, eg.:

setTimeout(function () { yourCode... }, 5000);

However, that is rarely the proper solution. Instead, you should look in the API of your data source, it probably has a callback function you can use to get notified of the data being available. That's the proper way to wait for data. If there's no such way, you'll have to use setTimeout (in fact, call it again if data isn't available yet when you get inside the delayed code).

Sign up to request clarification or add additional context in comments.

1 Comment

I'll take a look at the docs, but this works great for what I need. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.