Google maps geocode API V3 not returning result in javascript function

自古美人都是妖i 提交于 2019-11-29 07:35:21

If you are using V3 of the API cannot you use the this?

function findAddressViaGoogle() {
    var address = $("input[name='property_address']").val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            newPointClicked(results[0].geometry.location)
        } else {
            alert("Unable to find address: " + status);
        }
    });
}

The above is what I use to find some lat long cordinates of an inputted address, May work better?

EDIT:

function loadFromSearch(address) 
{
midpoint = getLatLong(address);
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}


function getLatLong(address) 
{
    var geocoder = new google.maps.Geocoder();
    var result = "";
    geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            result = results[0].geometry.location;
        } else {
            result = "Unable to find address: " + status;
        }
    });
    return result;
}

The problem is your $.getJSON function is asynchronous, yet you are returning the 'result' synchronously.

You need to do something like this (not tested!)

function loadFromSearch(address) 
{
  midpoint = getLatLong(address, function(midpoint){
    // this is a callback
    mapCentre = midpoint;
    map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    ...           
    });
}

function getLatLong(address, callback) 
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,
  function (data) {
    if (data.status == "OK") {
        result = data.results[0].geometry.location;
        callback(result) // need a callback to get the asynchronous request to do something useful 
    }
  });
}

In response to your edit: Oh dear, it looks like the V3 geocoder does not support JSONP. This means you can not do a cross-domain request to get data from it in your browser. See http://blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice/

However Brady's solution does work. I guess that is the way Google want us to geocode now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!