Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

geolocation - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...