繁体   English   中英

Geocoder Geocode-Google Maps JavaScript API

[英]Geocoder Geocode - Google Maps javascript API

我对以下功能有疑问:

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

它返回我“未定义”。 任何帮助将不胜感激。 非常感谢!

实际上,您的地理编码代码是正确的。 问题是“ geocoder.geocode”是异步的,并且geo函数在获取地理编码结果之前完成了执行。 作为概念证明,请尝试以下操作:

function geo(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            alert(results[0].geometry.location); //should have valid info
            return results[0].geometry.location;                    
        }
    });

    alert("I bet you were not expecting this alert to go first");                
}

因此,您有两个选择。 您可以在geo函数中处理地理编码位置,也可以提供一个回调函数来处理该位置。

我用一个例子更新了你的小提琴。 在这里检查

好,谢谢。

我找到了其他解决方案-最好将results [0] .geometry.location中的值保存到cookie并在需要的地方使用。 不管怎么说,还是要谢谢你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM