【问题标题】:Understanding geocoding in Javascript理解 Javascript 中的地理编码
【发布时间】:2011-05-17 21:19:45
【问题描述】:

好的,我在 jQuery 应用程序中设置了 Google 地图。 (V3)。我可以整天对地图进行地理编码。

所以,我想我会很聪明,将实际的地理编码功能转移到一个函数中。

这是我正在使用的功能:

功能地理编码(地址){ 变种自我=这个; geocoder.geocode({'地址':地址},功能(结果,状态){ 控制台.log(状态); 如果(状态 == google.maps.GeocoderStatus.OK){ 返回结果[0].geometry.location; } 否则 { 返回空值; } }); 返回“WTF?”; }

“WTF”是你马上就会看到的笑话。

现在,稍后在我的代码中,我尝试像这样调用函数:

var start_latlng; start_latlng = 地理编码(开始地址); 控制台.log(start_latlng);

我在控制台中得到的是:

怎么回事? 好的

请注意“WTF”在“OK”之前,即使我在函数中打印“OK”。 (console.log(status))

我的猜测是因为地理编码需要一点时间才能返回,并且函数会在返回第一个地理编码值之前继续运行。

是否有人对如何改进这一点有任何建议,以便我的“start_latlng”包含预期值?

感谢您的任何指点。

* 编辑**

这就是我最终要做的。

我这样调用函数:

地理编码(开始地址,功能(数据){ start_latlng = 数据; 控制台.log(start_latlng); });

这是新功能(尚未完成,但你明白了)

功能地理编码(地址,回调){ geocoder.geocode({'地址':地址},功能(结果,状态){ 如果(状态 == google.maps.GeocoderStatus.OK){ 回调(结果[0].geometry.location); } 别的 { 回调(“错误”); } }); }

像魅力一样工作。 :-)

感谢您的提示并帮助我思考更好。

【问题讨论】:

    标签: jquery geocoding


    【解决方案1】:

    geocode() 期望的是一个回调函数作为它的参数。这意味着它的调用结果将异步传递给您指定的函数当它准备好时,而不是作为return 值。

    function geocode(address) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                /* do whatever you need to do with the results here */
            }
            else {
                /* handle the error */
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      地理编码器似乎在异步工作,因此结果不足为奇。我的意思是,执行流过地理编码器调用的点,因此函数返回,随后地理编码器返回其结果 - 这就是为什么您按该顺序获得输出的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多