承诺使用Google Maps Geocoder API

Myk*_*l_M 6 javascript google-maps google-maps-api-3 es6-promise

我正在尝试创建一组函数,使用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;
            }
       })
  }
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的任何帮助或指示!

Mar*_*yer 11

您的主要问题是geocoder.geocode()异步并进行回调.您正在将函数传递给回调,但将返回值视为将从main函数返回findLatLang(),但它不会.目前findLatLang()没有返回.

findLatLang() 你应该有承诺并从函数返回它:

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));
            }
    })
    })
} 
Run Code Online (Sandbox Code Playgroud)

然后在循环中getPoints()你可以将这些promises收集到一个数组中并调用Promise.all()数组,这将在所有promises已经解析后为你提供值:

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);
})
Run Code Online (Sandbox Code Playgroud)

目前还不清楚它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);
Run Code Online (Sandbox Code Playgroud)
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Run Code Online (Sandbox Code Playgroud)