从函数内部的函数返回值
我正在使用 goMap 并尝试在其中添加一个函数,但在调用该函数时无法让它返回。如果我在函数内使用 alert()
,它会返回我需要的值。
getAddress: function(latlngcoords)
{
var goMap = this;
var input = latlngcoords;
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
var address;
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
if(results)
{
address = results;
//alert(address); <-- works but
}
}
});
return address; // won't return at all?
},
它是通过执行以下操作来调用的: $.goMap.getAddress()
但参数中包含纬度和经度。我需要它通过返回地址
返回值,但它根本不会返回任何内容。
我怎样才能让它返回值?
I'm using goMap
and I'm trying to add a function inside it, but I cannot get it to return when the function is called. If I use alert()
inside the function, it has the values I need it that should be returned.
getAddress: function(latlngcoords)
{
var goMap = this;
var input = latlngcoords;
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
var address;
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
if(results)
{
address = results;
//alert(address); <-- works but
}
}
});
return address; // won't return at all?
},
It's called by doing: $.goMap.getAddress()
but with a latitude and longitude in the argument. I need it to return the values by return address
but it won't return anything at all.
How will I be able to get it to return the value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
geocode
是一个异步函数。当您调用它时,它就会启动,但仅此而已。 (这就是它接受回调的原因。)因此,您的getAddress
函数在回调设置address
之前返回。您需要让您的 getAddress 函数也接受回调,并以这种方式返回结果,例如,
自然这意味着代码调用
getAddress
必须处理 getAddress 也是异步的这一事实。geocode
is an asynchronous function. It starts when you call it, but that's all. (That's why it accepts a callback.) So yourgetAddress
function is returning beforeaddress
is set by the callback.You need to have your
getAddress
function accept a callback as well, and return the result that way, e.g.Naturally this means that the code calling
getAddress
has to handle the fact thatgetAddress
is also asynchronous.