好的,我在 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"); } }); }
就像魅力一样。 :-)
感谢您的提示并帮助我更好地思考。
最佳答案
geocode()
期望的是回调函数作为其参数。这意味着它的调用结果将在准备好时异步传递给您指定的函数,而不是作为返回
值。
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 */
}
});
}
关于jquery - 了解 Javascript 中的地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314270/