javascript google maps Geocoder调用者函数在被调用者函数之前结束
我在javascript上开发geocoder。我有一个名为codeAddress的函数,它获取地址并正确给出坐标。然而,当我在另一个函数中调用此函数时,我无法得到正确的结果,因为调用方函数在codeAddress函数之前结束。 这是我的密码:javascript google maps Geocoder调用者函数在被调用者函数之前结束,javascript,google-maps,geocode,Javascript,Google Maps,Geocode,我在javascript上开发geocoder。我有一个名为codeAddress的函数,它获取地址并正确给出坐标。然而,当我在另一个函数中调用此函数时,我无法得到正确的结果,因为调用方函数在codeAddress函数之前结束。 这是我的密码: var geocoder = new google.maps.Geocoder(); var lokasyon ={ id:0,lat:0,lng:0 }; var lokasyonlar=[]; function cod
var geocoder = new google.maps.Geocoder();
var lokasyon ={ id:0,lat:0,lng:0 };
var lokasyonlar=[];
function codeAddress(adres, id) {
geocoder.geocode({ 'address': adres }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lokasyon.id = id;
lokasyon.lat = results[0].geometry.location.lat();
lokasyon.lng = results[0].geometry.location.lng();
lokasyonlar.push(lokasyon);
alert("codeAddress");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function trial2() {
codeAddress("1.ADA SOKAK, ADALET, OSMANGAZİ, Bursa", 12);
alert("trial2");
}
window.onload = trial2;
当我运行这段代码时,首先显示“trial2”,然后显示“codeAddress”。原因是什么?因为geocoder.geocode()方法请求Google服务器,这需要几秒钟的时间。
这意味着geocode()方法是异步的,并且alert(“trial2”)比callback快
如果要在回调后执行代码“alert”(“trial2”),则需要进行如下更改:
function codeAddress(adres, id, callback) {
geocoder.geocode({ 'address': adres }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lokasyon.id = id;
lokasyon.lat = results[0].geometry.location.lat();
lokasyon.lng = results[0].geometry.location.lng();
lokasyonlar.push(lokasyon);
alert("codeAddress");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
callback();
});
}
function trial2() {
codeAddress("1.ADA SOKAK, ADALET, OSMANGAZİ, Bursa", 12, function(){
alert("trial2");
});
}