[英]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.