I was wondering if its possible to geocode something using googlemaps api synchronously so instead of waiting for a callback function to be called, it would wait for a value to be returned. Has anyone found a way to do something like this.
P.S.: I'm using version 3 of the api
The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced. Along with the overall Google Terms of Use, there are usage limits specific to the Geocoding API.
Geocoding is the process of converting addresses (like a street address) into geographic coordinates (like latitude and longitude), which you can use to place markers on a map, or position the map.
Yes, what you are trying to achieve is possible, although a synchronous request is not needed.
Look at this code
function StoreGeo()
{
var address = $('input[name=zipcode]').val() + ', ' + $('input[name=city]').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var ll = results[0].geometry.location.toString();
llarr = ll.replace(/[\(\) ]/g, '').split(',');
for(i = 0; i < llarr.length;i++)
{
$('#form').append($('<input type="hidden" name="'+(i == 0 ? 'lat' : 'long')+'">').val(llarr[i]));
}
$('#form').submit();
}
else
{
alert(status);
}
});
$('#form').unbind('submit');
return false;
}
$(document).ready(function () {
//init maps
geocoder = new google.maps.Geocoder();
$('#form').bind('submit',function() {
StoreGeo();
});
});
So, attach submit handler to the form, when it is submitted do the geo request based on the address info from your form. But at the same time postpone submitting by returning false in the handler. The response handler will make 2 hidden textfields 'lat' and 'long' and store the response. finally the form is submitted by client script, including the two new fields. At the server side you can store them in the DB.
!! Note that this is possible, but is probably against the google terms, like noted above.
The Geocoder calls your callback function with the value. That's the only way to do it. If it were synchronous, your script would freeze while it waited for the Geocode to process. There really isn't any reason to do it like that.
What exactly are you trying to accomplish?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With