views:

535

answers:

2

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

+1  A: 

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?

Chris B
I have a form which includes an address. As part of validating the form data, I was thinking of using googles geocoder to check the address. I also need the latitude, longitude values to input into my database. I know I can do this using the callback function, but that seems like a hack and would be more complicated.
bobbyb
The Geocoder is entirely intended to be used with the callback function. Don't worry, it's not a hack. :) It's really your only option. Do keep in mind, however, that you will be breaking the Google Maps Terms of Service if you are using the Geocoder without somehow displaying the results on a Google Map.
Chris B
far as I know, you can not use the google api in an internal system or with a select audience. Your page that uses the Maps should be open to the entire internet - read the terms of contract. Good @B Chris @Chris B
Ph.E
A: 

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.

karremans