[英]Asynchronous function call in Javascript
我的问题是这个。我是javascript新手。 我有一个函数可以异步调用Google Map API(它会根据latlng返回位置)。我的代码中的该函数是MarkerCreaterPlusLocation 。 该调用返回我在代码中名为MarkerCreater的另一个函数中需要的值。 但是问题在于MarkerCreater不会停止让MarkerCreaterPlusLocation返回值。
为了克服此问题,我尝试使用MarkerCreater的回调在异步函数返回值时执行
结构如下:
google.maps.event.addListener(map, 'click',addLatLng); //This code attaches the function to Listener
function addLatLng(event) {
path = poly.getPath();
path.push(event.latLng);
MarkerCreaterPlusLocation(event.latLng,MarkerCreater);//MarkerCreater is the callback function
}
function MarkerCreaterPlusLocation(input,callback){
location="l";
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
location=results[1].formatted_address;
callback(location,input);//I call the callback function upon the success of the result or otherwise
} else {
location="l";
callback(location,input);
}
} else {
location="l";
callback(location,input);
}
});
}
function MarkerCreater(l,x){
var marker = new google.maps.Marker({
position: x,
title: '#' + path.getLength()+l,
icon: 'images/beachflag.png',
map: map
});
///Some more javascript code
}
我想我在这里犯错了,因为这似乎不起作用。 相反,它给出了404错误,这使我更加难以理解它。 请帮忙
您的location
变量未使用var
声明,这意味着它在全局范围内(即window)。 因此,设置location
实际上是在设置window.location
,这将导致重定向到404。
要解决此问题,请将您的MarkerCreaterPlusLocation函数的第一行更改为:
var location="l";
这将仅在函数范围内而不在窗口范围内创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.