Reputation: 1623
I am using google maps geocoder which uses an asynchronous to return the lat and lng values. It works perfect. I then want to pass those lat lng values to an ajax call to my database to search against. I can't figure out though how to know when the asynchronous part is done to then run the ajax portion.
lat and lng are always empty when this runs.
Is there a better way to do this?
function getLatLng(address, fn){ geocoder.geocode( { 'address': address}, function(results, status) { fn(results[0].geometry.location.lat(),results[0].geometry.location.lng()); }); } getLatLng(address, function(lat,lng){ var formData = $('#form').serialize(); if (lat!='' && lng!='') { $.ajax({ type: "POST", url: "/_templates/map_ajax", dataType:'json', data: formData, error: function() { $('#status').text('Update failed. Try again.').slideDown('slow'); }, success: function(formData) { buildMarkers(formData); } }); //ajax close } }); // close getLatLng
Upvotes: 0
Views: 1443
Reputation: 2554
As I see it, the only thing wrong with your code is that you never post the lat/lng values to your AJAX service, you're only sending the serialized form data. I simplified your example to something like:
function getLatLng(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location.lat(),results[0].geometry.location.lng());
});
}
getLatLng("new york", function(lat,lng){
if (lat!='' && lng!='') {
console.log(lat);
console.log(lng);
}
});
Upvotes: 1