0

我需要使用以下代码获取城市的 latlng 值......但我得到的结果是“latlng 值未定义”我的代码是

geocoder.geocode( {'address': acity}, function(results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
                 latlng1 = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
              }
        });

更新:如果我分别显示 lat 和 lng 值,则它已显示,如果将它们分配给 latlng1 “latlng1 未定义”,则显示

4

2 回答 2

0

根据文档,该位置作为 LatLng 对象返回。您不需要创建新的 LatLng 对象。

几何包含以下信息:

location 包含地理编码的纬度、经度值。请注意,我们将此位置作为 LatLng 对象返回,而不是作为格式化字符串。

例子:

geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        window.test = results[0].geometry.location
         setTimeout(function() {
             console.log(window.test.lat());
             console.log(window.test.lng());
         }, 5000)
      } 
    });

编辑:我想我误解了,我想你只是想要全局范围内的 latLng 对象。我已经编辑了这个例子。

于 2013-04-08T13:33:42.157 回答
0

如果我理解你的话,你正在尝试做这样的事情:

var latlng1;

geocoder.geocode({
    'address': acity
}, function( results, status ) {
    if( status == google.maps.GeocoderStatus.OK ) {
        latlng1 = new google.maps.LatLng(
            results[0].geometry.location.lat(),
            results[0].geometry.location.lng()
        );
    }
});

// Now do stuff with latlng1 here

这永远不会奏效,而且你也无法让它发挥作用。正如您所发现的,“现在使用 latlng1 进行操作”代码在收到结果之前运行。

地理编码器 API 与访问服务器获取数据的任何 JavaScript API 一样,是异步的。API调用立即返回,数据准备好时调用回调函数。

所以你需要做的是在数据准备好时调用LatLng你自己的函数,像这样(也简化以删除冗余的构造函数调用):

geocoder.geocode({
    'address': acity
}, function( results, status ) {
    if( status == google.maps.GeocoderStatus.OK ) {
        doStuffWithLatLng( results[0].geometry.location );
    }
});

function doStuffWithLatLng( latlng ) {
    // Now do stuff with latlng1 here
}

或者,您当然可以将“do stuff”代码放在地理编码器回调中:

geocoder.geocode({
    'address': acity
}, function( results, status ) {
    if( status == google.maps.GeocoderStatus.OK ) {
        var latlng1 = results[0].geometry.location;
        // Now do stuff with latlng1 here
    }
});
于 2013-04-08T16:15:36.807 回答