11

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

giroy
  • 2,203
  • 6
  • 27
  • 38

3 Answers3

7

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
  • 71
  • 1
  • 2
  • 1
    great answer! I would add that you can do the geo request as soon as the user provides the needed info (or with some time out after that). So while he completes the rest of the form the Geocoder has time to send the reply. You will make more geo requests like this, if the user keeps changing his mind. – GoTo Jun 12 '13 at 21:43
  • As for google terms, I don't think that you break them if you simply store the answers in a database. Pretty much any kind of webapp that goes beyond a simple example will require you to store the answers in a database. You break them if you use the answers without the Google Maps, or in a closed/internal system. – GoTo Jun 12 '13 at 21:48
2

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
  • 15,524
  • 5
  • 33
  • 40
  • 1
    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. – giroy Aug 21 '09 at 14:24
  • 1
    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 Aug 21 '09 at 14:53
  • 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 – kran1um Jun 28 '10 at 15:13
  • 11
    stop saying "there really isn't any reason to do X". There's always some reason. In this case the user might browse away (with the submit button) before the Geocoder replies. – GoTo Jun 12 '13 at 21:40
  • @GoTo There is never any reason to completely freeze up the browser. If you really needed to prevent them from doing something while waiting for the callback, you can do that manually. The user should still be able to scroll around or access other functionality. – Chris B Jun 13 '13 at 14:32
  • @ChrisB I agree. One would manually block actions that need the response from geocoder. And then manually timeout if the geocoder is down... – GoTo Sep 24 '13 at 21:35
1

I simply use a flag during form submit to know when submit should pass or when it should wait for geocoding. When geocoding is done it will then re-submit the form again.

    var hasGeocoded = false;

    searchFrom.on('submit', function(){
        //If not geocoded yet
        if (!hasGeocoded) {
            var geocoder = new google.maps.Geocoder();
            var location = locationEl.val();
            geocoder.geocode({'address': location}, function (results, status) {
                hasGeocoded = true;

                if (status == google.maps.GeocoderStatus.OK) {
                    $('#coords').val(
                        results[0].geometry.location.lat() + ',' + results[0].geometry.location.lng()
                    );
                }

                searchFrom.submit();
            });

            return false; //wait for geocoder to finish and re-submit the form
        }

        return true;
    });
Pavel Dubinin
  • 2,410
  • 1
  • 24
  • 28