地理编码器不返回城市的值

Geocoder not returning the value of the city

本文关键字:城市 返回 编码器      更新时间:2023-09-26

我的map.js文件中有一个名为getNameOfCity()(函数如下)通过执行以下var city = getNameOfCity();从我的操作.js文件中调用它,然后我提醒城市,它说未定义。

这是地图中的函数.js

function getNameOfCity() {
    geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]){
                jQuery.each(results[0].address_components, function(key, value){
                    if(value.types[0] == 'locality') {
                        return value.long_name;
                    }
                });
            }
        } else {
            return false;
        }
    });
}

当我在返回之前提醒value.long_name正确的城市时。但是当我从调用函数的位置向城市发出警报时,它返回未定义。有什么想法吗?

谢谢

你在匿名函数中返回一个值 - 所以你把它返回为空。

你需要做的是在返回响应时调用一个函数,说"我完成了,这是城市名称"。

正如亚当所说,问题是你返回到匿名函数。 请改为执行以下操作:

function getNameOfCity() {
    var city = '';
    geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]){
                jQuery.each(results[0].address_components, function(key, value){
                    if(value.types[0] == 'locality') {
                        city = value.long_name;
                    }
                });
                return city;
            }
        } else {
            return false;
        }
    });
}

更新回调方式,正如您所建议的那样...

function getNameOfCity(callback) {
    geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]){
                jQuery.each(results[0].address_components, function(key, value){
                    if(value.types[0] == 'locality') {
                        callback(value.long_name); // call the function, pass the city name.
                    }
                });
            }
        } else {
            callback(false); // not found? pass false instead.
        }
    });
}

更新 2
现在,您可以使用此函数以这种方式获取城市名称:

getNameOfCity(function(city) {
    alert(city);   // or do something less useless.
});