【问题标题】:Get country and state name from lat and lng in Geocode [duplicate]从地理编码中的 lat 和 lng 获取国家和州名称 [重复]
【发布时间】:2021-05-11 14:48:50
【问题描述】:

我是网络开发的新手。今天,我正在尝试使用 Google Map API 使用 JavaScript 从经度和纬度获取国家名称和州名称。我从 Google Map API 阅读了文档并做了一些研究,但我对此有点困惑。我试了一下,这就是我所做的:

function getCountryName(latitude, longitude){
    var country;
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({location: {lat: latitude, lng: longitude}}, (results, status) => {
        if(status === "OK"){
            if(results[0]){
                country = results[0].address_components[0].types[0].country;
            }
            else{
            country = "N/A";
            }
        }
    });
    return country;
}

但是,我不断收到“未定义”的结果。我的方法有什么问题吗? 提前谢谢大家!

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    您似乎对这里发生的异步编程感到困惑。

    基本上你在函数执行结束时有return country; 语句,由于那时还没有获取结果,所以它总是未定义的。

    您发送到geocoder.geocode 的第二个参数是一个回调函数,一旦 google 获取结果就会被调用,这显然需要一点时间。

    所以你的函数应该是这样的

    function getCountryName(latitude, longitude, onSucess){
        const geocoder = new google.maps.Geocoder();
        geocoder.geocode({location: {lat: latitude, lng: longitude}}, (results, status) => {
            if(status === "OK"){
                if(results[0]){
                    onSucess(results[0].address_components[0].types[0].country);
                }
                else{
                    onSucess("N/A");
                }
            }
        });
        return country;
    }
    

    而当你要在别处使用这个功能的时候,你必须这样使用它

    getCountryName(1.1111, 2.2222, (country) => {
        alert(country);
        console.log(country);
        // You can do anything here like showing it to ui or using it elsewhere
    }
    

    如果您想了解更多关于 JS 回调的信息,请浏览此Article

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多