首页 文章

了解Javascript中的地理编码

提问于
浏览
3

好的,我在jQuery应用程序中安装了Google Map . (V3) . 我可以整天对 Map 进行地理编码 .

所以,我认为我会很聪明,并将实际的地理编码功能转移到一个功能中 .

这是我正在使用的功能:

function geocode(address) {
        var self = this;
        geocoder.geocode( { 'address': address }, function(results, status) {
            console.log(status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
            } else { return null; }
        });
        return "WTF?";
    }

“WTF”是一个笑话,你马上就会看到 .

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

var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);

我在控制台得到的是:

WTF?
OK

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

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

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

谢谢你的任何指示 .

编辑*

这就是我最终做的事情 .

我这样调用函数:

geocode(start_address, function(data) {
            start_latlng = data;
            console.log(start_latlng);          
        });

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

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

奇迹般有效 . :-)

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

2 回答

  • 3

    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 */
            }
        });
    }
    
  • 1

    地理编码器似乎异步工作,因此结果并不令人惊讶 . 我的意思是,执行流经地理编码器调用点,因此函数返回,随后地理编码器返回其结果 - 这就是您按顺序获得输出的原因 .

相关问题