javascript - Google Maps Geocoder API 的 promise

标签 javascript google-maps google-maps-api-3 es6-promise

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

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

我听说 javascripts promises 可以解决这类问题,所以我做了一些研究,但它似乎对解决问题没有帮助。我是 promises 的新手,所以如果我以错误的方式解决这个问题,请原谅。

相关代码如下

 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() 是异步的并接受回调。您正在将一个函数传递给回调,但将返回值视为它将从主函数 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() 的循环中,您可以将这些 promise 收集到一个数组中,然后在数组上调用 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 的来源 - 您在函数中使用它,但它没有被传递到任何地方。

proof of concept fiddle

代码片段:

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>

关于javascript - Google Maps Geocoder API 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46064244/

相关文章:

javascript - Jquery 点击处理程序两次后不工作

javascript - 如何永久停止 jshint 'read only' 警告/错误?

javascript - ionic 应用程序中的计时器(setInterval)在后台运行一段时间后进入休眠状态

javascript - Google Map API 创建独特信息窗口时出现问题

javascript - 为什么按索引插入节点的方法不起作用?

google-maps - Google Maps Static API 返回奇怪的图像

google-maps - -canOpenURL : failed for URL: "comgooglemaps://" - error: "The operation couldn’ t be completed.(OSStatus 错误 -10814。)”

android - 将 3D 对象添加到 map 并在其周围平移

Android:根据颜色检查谷歌地图标记是否存在

javascript - 在谷歌地图 Angular 查找距离