我希望你能提供帮助。我做了一个函数,接收一个lnglat点对象,只返回城镇。我可以让它在console.log中打印正确的城镇,但它不会从函数返回数据。
我知道这将是一个基本错误,但有人可以查看代码,请告诉我。
提前致谢。
function getTownFromPoint(point){
var geocoder ;
var geocoder = new google.maps.Geocoder();
var townset = false;
mylocation = "";
geocoder.geocode({latLng: point}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var components=results[0].address_components;
for (var component=0;component<(components.length);component++){
if(components[component].types[0]=="country" & !townset){
mylocation = components[component].long_name;
}
if(components[component].types[0]=="postal_code" & !townset){
mylocation = components[component].long_name;
}
if(components[component].types[0]=="locality"){
mylocation = components[component].long_name;
townset = true;
console.log(mylocation);
}
}
}
}
});
return(mylocation);
}
答案 0 :(得分:1)
Geocoder是异步的 - 您在设置值之前返回值。
答案 1 :(得分:0)
那是因为geocode
是一个ajax
来电并且它们是异步的。您需要提供回调函数或使用promise来获取数据。由于您的问题看起来没有使用jQuery
,因此回调可能会更容易:
这是代码的简化版本,其中包含如何使用回调函数的示例:
// we pass in the callback as a function parameter
function getTownFromPoint(point, callback) {
geocoder.geocode({
latLng: point
}, function (results, status) {
var myLocation = results.myLocation;
// then we call the callback with the myLocation variable
callback(mylocation);
}
);
}
// call the function with the point variable and the function
// we will use for our callback
getTownFromPoint(1.223, function (myLocation) {
console.log(myLocation)
});
答案 2 :(得分:0)
您遇到的问题是您在执行返回结果之前将geocoder.geocode函数视为立即完成。真正发生的是触发geocoder.geocode,然后立即返回结果。由于异步结果很可能未返回,因此结果为空。将地理编码结果视为推动而非拉动。 storeResult函数(未显示)是保存信息所需的任何代码。因为您要将结果与错误字符串组合在一起,所以您必须在storeResult函数中处理它。作为替代方案,您可以在结果中显示指示成功或失败的状态。
存储结果:
storeResult(result);
在你的功能中使用这个功能。这将解决您的问题