Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API Geocode Synchronously

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

like image 806
giroy Avatar asked Aug 21 '09 05:08

giroy


People also ask

Is Google's geocoding API free?

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.

What is Geocoder map?

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.


2 Answers

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.

like image 153
karremans Avatar answered Oct 02 '22 04:10

karremans


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?

like image 24
Chris B Avatar answered Oct 02 '22 05:10

Chris B