I'm working on someone else's code, and I am trying to use Google maps API to convert a street address into latitude and longitude coordinates: var start_lng; var end_lat; var end_lng; getLat(start); getLng(start);
function getLat(loc) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
alert(lat);
return lat;
//alert(start_lng);
}
else {
alert("Error");
}
});
}
function getLng(loc) {
var geocoder_lng = new google.maps.Geocoder();
geocoder_lng.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lng = results[0].geometry.location.lng();
alert(lng);
return lng;
}
else {
alert("Error");
}
});
}
So far, so good. In the code below, I take that latitude and longitude and perform various calculations with them:
alert("DO REST");
var start_p = new google.maps.LatLng(start_lat, start_lng);
alert(start_p);
var end_p = new google.maps.LatLng(end_lat, end_lng);
The problem is that since the call that gets the latitude and longitude is asynchronous, the code below doesn't wait to get the values before it tries to use them. They show up as undefined. I tried putting the second half of the code in its own function and calling that at the end of the longitude request, but that only worked if the longitude call happened to finish first. I also tried $.ajax({ async:false}) but that didn't do anything. This is my first time dealing with AJAX, so I'm really not sure which way to go.
See Question&Answers more detail:os