【问题标题】:JavaScript Geocoding does not start searchJavaScript 地理编码不开始搜索
【发布时间】:2012-10-23 10:44:58
【问题描述】:

我目前正在将谷歌地图的一些功能移动到一个单独的文件中。在我的另一个文件中,我创建了一些主函数 search(),在其中我创建了包含另一个文件的这个工作流。 我遇到的问题是 geocoder.geocode() 函数,直到今天它都运行良好,但我不知道出了什么问题。地理编码器被创建,然后跨过函数 geocoder.geocode() 而不实际做任何事情。有人有想法吗?

这是我的主要文件.js 的一部分:

//set the point.
var latlng = new google.maps.LatLng(55.379, -3.444);
//initialize the google map.
initializeMap(latlng, null, null, null);
//get selected country text from dropdown.
var address = $('#country option:selected').text();
//get entered postcode from textbox.
if ($("#postcode").val() != "") {
    address = $('#postcode').val() + ", " + address;
}
//do a google search and store the result.
var result = googleSearch(address);

地址类似于:“NX5 897,美国”。 这是functionCollection.js中的googleSearch

 function googleSearch(address) {

    var result;

    //setting up a geocoder search.
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            result = results[0];
        }
        else {
            alert("Geocode was not successful for the following reason: " + status);
            result = null;
        }
    });
    return result;
}

【问题讨论】:

    标签: javascript jquery function google-maps geocoding


    【解决方案1】:

    您正在返回异步请求 geocoder.geocode() 的结果。 向 googleSearch 发送回调或仅从函数中调用您的函数。

       geocoder.geocode({ address: address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        result = results[0];
    }
    else {
        alert("Geocode was not successful for the following reason: " + status);
        result = null;
    }
    somefunction(result); or callback(result)
    

    });

    【讨论】:

    • 测试你可以在给定的地方用 alert(result) 替换一些功能。
    • 问题是 geocoder.geocode() 甚至没有到达我在那里创建的函数,你建议我在其中添加这个回调。它创建了一个地理编码器,但它有点跳过了整个事情,如果我看看最后的结果,它仍然是未定义的。
    • 你没有明白这一点,你使用 geocoder.geocode() 异步向谷歌服务器发送请求,这意味着一旦你调用 geocoder.geocode() 你立即移动返回结果步骤,这当然还没有评估,因为你还没有收到谷歌的回复。 Google 在回调函数(结果、状态)中向您发送回复。在我建议过的地方放置警报并查看。
    • 我已经测试了你的建议,var 结果仍然是未定义的,即使我用它去另一个函数,正如你告诉我的那样。
    • 这个答案是正确的,你需要了解异步函数的本质。
    【解决方案2】:

    这里

    geocoder.geocode({ address: address },
    

    您将变量address 传递了两次。

    将变量名更改为其他名称,例如 myaddress 并尝试

    geocoder.geocode({ address: myaddress },
    

    【讨论】:

    • 我认为可能也是这样,但我可以将变量名地址更改为任何内容,但它仍然不起作用。我还尝试了它所在的版本:geocoder.geocode({ 'address': address } 但它没有用。
    猜你喜欢
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多