[英]Promises With Google Maps Geocoder API
我正在尝试创建一组函数,使用Google Maps Geocoder API将一组地址转换为lat long值。
目前,我已成功将地址转换为lat long值,但函数在返回之前完全执行。 我知道这是因为它在之后记录正确的lat long值之前会抛出未定义的错误。
我听说javascripts承诺可以解决这类问题所以我做了一些研究,但它似乎没有帮助解决问题。 如果我以错误的方式解决这个问题,我很同意这个承诺。
这是相关的代码
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;
}
})
}
在此先感谢您的任何帮助或指示!
您的主要问题是geocoder.geocode()
是异步的并且需要回调。 您正在将函数传递给回调,但将返回值视为将从main函数findLatLang()
,但它不会。 目前findLatLang()
什么都不返回。
findLatLang()
是您应该拥有promise并从函数返回它的地方:
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));
}
})
})
}
然后在getPoints()
的循环中,您可以将这些promises收集到一个数组中,并在数组上调用Promise.all()
,这将在所有promise已经解析后为您提供值:
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);
})
目前还不清楚addressData
的来源 - 您在函数中使用它,但它并没有在任何地方传递。
代码段:
var geocoder; var map; var addressData = [{ location: "New York, NY, USA" }, { location: "Newark, NJ, USA" }]; function initialize() { var map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); var coordinates = [{}]; var geocoder = new google.maps.Geocoder(); var bounds = new google.maps.LatLngBounds(); 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)); } }) }) } 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); coordinates = returnVals; returnVals.forEach(function(latLng) { console.log(latLng); var marker = new google.maps.Marker({ position: { lat: latLng[0], lng: latLng[1] }, map: map }); bounds.extend(marker.getPosition()); map.fitBounds(bounds); }) }) } google.maps.event.addDomListener(window, "load", initialize);
html, body, #map_canvas { height: 100%; width: 100%; margin: 0px; padding: 0px }
<script src="https://maps.googleapis.com/maps/api/js"></script> <div id="map_canvas"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.