gpt4 book ai didi

javascript - Google 地理编码异步方法中的 Firebase 更新

转载 作者:行者123 更新时间:2023-12-03 03:54:55 24 4
gpt4 key购买 nike

我正在尝试编写一种在地理编码函数完成后更新我的 Firebase 数据库的方法。我正在 Angular2 中编写代码,因此我的 Firebase 数据库是在我的构造函数中定义的。我知道问题出在异步函数上,但我不确定如何解决这个问题。这是我的代码:

geocoding(callback){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': this.loc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback([results[0].geometry.location.lat(), results[0].geometry.location.lng()]);
} else {
this.lat = 0;
}
});
}

和:

geocode(){
this.geocoding(function(latLng){
this.db.object('users/' + this.auth.id).update({
lat: latLng[0],
lng: latLng[1]
});
});
}

最佳答案

我知道怎么做了。原来你需要使用 promise ,这里是工作代码:

geocode(address){
return new Promise(function(resolve,reject){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
resolve(results);
} else {
this.lat = 0;
}
});
});
}

和:

  this.geocode(this.loc).then(results => {
this.db.object('users/' + this.auth.id).update({
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
});
});

关于javascript - Google 地理编码异步方法中的 Firebase 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com