Google Maps Geocoder API承诺 [英] Promises With Google Maps Geocoder API

查看:145
本文介绍了Google Maps Geocoder API承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一组函数,使用Google Maps Geocoder API将一组地址转换为经纬度值。

目前,我已经成功地将地址转换为lat long值,但函数在返回之前完全执行。我知道这一点,因为它在之后记录正确的经纬度值之前抛出未定义的错误。

我听说javascripts promises可以解决这类问题,所以我做了一些研究,但似乎没有帮助解决这些问题。 Im新承诺,所以如果我以错误的方式进行讨论,请原谅我。



这里是相关的代码

 函数getPoints(geocoder,map){
let locationData = [];
let latValue;
for(let i = 0; i< addressData.length; i ++){
let getLatLong = new Promise(function(resolve,reject){
latValue = findLatLang(addressData [i] (latValue!= undefined){
resolve(latValue());
} else {
reject();
}
});
getLatLong.then(function(){
console.log(latValue);
//返回一个GMap latLng对象
locationData.push(new google.maps.LatLng( latValue [0],latValue [1]));
})
}
return locationData;


函数findLatLang(address,geocoder,mainMap){
geocoder.geocode({'address':address},function(results,status){
if(status ==='OK'){
console.log(results);
return [results [0] .geometry.location.lat,results [0] .geometry.location.lng] ;
} else {
alert('Couldnt''t找不到位置'+地址);
return;
}
})
}

预先感谢您的帮助或指示! 并采取回调。您将一个函数传递给回调函数,但将返回值视为它将从主函数 findLatLang()返回,但它不会。目前 findLatLang()不会返回任何结果。


$ b

findLatLang()是你应该承诺并从函数中返回的地方:

pre $函数findLatLang(address, b $ b返回新的Promise(function(resolve,reject){
geocoder.geocode({'address':address},function(results,status){
if(status ==='OK' ){
console.log(results);
resolve([results [0] .geometry.location.lat,results [0] .geometry.location.lng]);
} else {
reject(new Error('Couldnt''t找不到位置'+地址));
}
})
})
}

然后在 getPoints()的循环中,您可以将这些承诺收集到一个数组中,并在数组中一次性地调用 Promise.all(),一旦所有的承诺都解决了,就会给出值:

 函数getPoints(geocoder,map){
let locationData = [];
let latValue;
for(let i = 0; i< addressData.length; i ++){
locationData.push(findLatLang(addressData [i] .location,geocoder,map))
}
return locationData //承诺数组
}

var locations = getPoints(geocoder,map)

Promise.all(locations)
。然后(函数(returnVals){
//当
//所有promise都已经解析
console.log(returnVals);
})$ b $时,您应该返回值b

目前尚不清楚 addressData 来自哪里 - 您在函数中使用它,但它没有被传递到任何地方。

Im trying to create a set of functions that translates a set of addresses to lat long values using the Google Maps Geocoder API.

Currently, I have it successfully translating the addresses to lat long values but the function fully executes before theyre returned. I know this because it throws undefined errors before it logs the proper lat long values after.

I heard that javascripts promises can be a solution to this type of problem so I did a little bit of research but it doesn't seem to be helping the issues. Im new to promises so excuse me if Im going about this in the wrong way.

Here`s the relevant code

 function getPoints(geocoder,map) {
       let locationData = [];
       let latValue;
       for(let i = 0; i < addressData.length; i++){
            let getLatLong = new Promise(function(resolve,reject){
                 latValue = findLatLang(addressData[i].location, geocoder, map);
                 if(latValue!=undefined){
                      resolve(latValue());
                 } else {
                      reject();
                 }
            });
            getLatLong.then(function(){
                 console.log(latValue);
                 //returns a GMap latLng Object.
                 locationData.push( new google.maps.LatLng(latValue[0],latValue[1]));
            })
       }
       return locationData;
  }

function findLatLang(address, geocoder, mainMap) {
       geocoder.geocode({'address': address}, function(results, status) {
            if (status === 'OK') {
                 console.log(results);
                 return [results[0].geometry.location.lat , results[0].geometry.location.lng];
            } else {
                 alert('Couldnt\'t find the location ' + address);
                 return;
            }
       })
  }

Thanks in advance for any help or pointers you would have!

解决方案

Your main issue is that geocoder.geocode() is asynchronous and takes a callback. You are passing a function to the callback but treating the return value as if it will return from the main function, findLatLang(), but it won't. Currently findLatLang() returns nothing.

findLatLang() is where you should have the promise and return it from the function:

function findLatLang(address, geocoder, mainMap) {
    return new Promise(function(resolve, reject) {
        geocoder.geocode({'address': address}, function(results, status) {
            if (status === 'OK') {
                console.log(results);
                resolve([results[0].geometry.location.lat , results[0].geometry.location.lng]);
            } else {
                reject(new Error('Couldnt\'t find the location ' + address));
            }
    })
    })
} 

Then in the loop in getPoints() you can just collect those promises into an array and call Promise.all() on the array which will give you the values once all promises have resolved:

function getPoints(geocoder,map) {
    let locationData = [];
    let latValue;
    for(let i = 0; i < addressData.length; i++){
        locationData.push(findLatLang(addressData[i].location, geocoder, map))
    }
    return locationData // array of promises
}

var locations = getPoints(geocoder,map)

Promise.all(locations)     
.then(function(returnVals){
        // you should have return values here when
        // all promises have rsolved
          console.log(returnVals);
})

It's not clear where addressData is coming from - you are using it in the function, but it's not being passed in anywhere.

这篇关于Google Maps Geocoder API承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆