Geocoder方法不返回值

时间:2014-01-06 13:11:43

标签: jquery api google-maps

从按钮单击调用时,Geocoder方法不会返回值。我需要将结果存储在全局变量“source_lat”和“source_long”中。在地理编码器返回值之前,似乎我的按钮点击结束了。

 function GeocoderStart(str) {
           geocoder = new google.maps.Geocoder();
               geocoder_request = { 'address': str };
               geocoder.geocode(geocoder_request, function (results, status) {
                   if (status == google.maps.GeocoderStatus.OK) {
                       var country = extractFromAdress(results[0].address_components, "country");
                       if ((country != "India") & (country != "")) {
                           //alert("Error", "The address you entered refers to <b>" + results[0].formatted_address + "</b>. Please select only addresses in India using the autocomplete lookup.");                        
                           alert("Please select a valid address");
                           return false;
                       } else {
                           source_lat = results[0].geometry.location.lat();
                           source_long = results[0].geometry.location.lng();
                       }
                   } else {
                       alert("Error", "Unable to lookup address for the following reason: " + status);
                       return false;
                   }                  
               });

}

//从地址函数中提取

 function extractFromAdress(components, type) {  // taken from http://stackoverflow.com/questions/8313876/more-efficient-way-to-extract-address-components
            for (var i = 0; i < components.length; i++)
                for (var j = 0; j < components[i].types.length; j++)
                    if (components[i].types[j] == type) return components[i].long_name;
            return "";
        }

1 个答案:

答案 0 :(得分:0)

下面是我如何在最近的项目中实现地理编码 - 也许它有助于揭示你所面临的问题:

$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=1600%20Pensyvania%20Ave%20Washington%20DC&sensor=false",
dataType = 'json',
function (data) {

    if (data['results']) {

         var country = data['results'][0]['address_components'][0]['long_name'];
         if ((country != "India") & (country != "")) {

            console.log("sorry, wrong country:)");

        } else {

            console.log("lat: " + data['results'][0]['geometry']['location']['lat'] + ",  lng: " + data['results'][0]['geometry']['location']['lng']);

        }
    }

});