Promises With Google Maps Geocoder API

后端 未结 1 1424
一生所求
一生所求 2020-12-15 13:47

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 t

1条回答
  •  有刺的猬
    2020-12-15 14:12

    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.

    proof of concept fiddle

    code snippet:

    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
    }
    
    

    0 讨论(0)
提交回复
热议问题