如何转换为Promise并使用Google Maps对地址进行地理编码

时间:2018-07-26 06:56:38

标签: promise vuejs2 vuetify.js vue2-google-maps

我要将这段代码转换为一个诺言

因为我想将经过地理编码的地址显示为vuetify

enter image description here

  

到目前为止,这是我的代码,其中包括google maps api和lodash。

<!DOCTYPE html>
    <html>
    <head>
        <title>Reverse Geocoding Sample</title>
    </head>
    <body>


        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>


    <script>

        function geocodelatLng(){
            var response = [
            {
                "address": "213 Marlon Forks\nSouth Corineland, HI 81723-1044",
                "lat": "10.30431500",
                "lng": "123.89035500"   
            },
            {
                "address": "1291 Stephania Road\nLake Dorotheastad, TN 82682-76",
                "lat": "10.30309100",
                "lng": "123.89154500"
            },
            {
                "address": "20330 Schmeler Course Apt. 210\nNorth Ari, NV 70048",
                "lat": "10.30356400",
                "lng": "123.89964100"
            }
            ] ; 




            return _.map(response,coords => { 
                // console.log(arr.index);

                var geocoder = new google.maps.Geocoder;


                var latLng = { 
                    lat : parseFloat(coords.lat),
                    lng : parseFloat(coords.lng)
                }  ; 


            // for every lat,lng . 
            // console.log(latLng);

            geocoder.geocode({'location': latLng},function (results,status){ 
                if (status === 'OK') {
                    if (results[0]) {
                        console.log(results[0].formatted_address);
                    } else {

                        window.alert('No results found');

                    }
                } else {
                    window.alert('Geocoder failed due to: ' + status);
                }

            });  





});
        }



    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6vKL6Q4u5ZhGAJlYOMkQZ13pxCUXOe9k&callback=geocodelatLng">
</script>
</body>
</html>

现在这会将所有内容记录到控制台,但是我的问题是我不知道如何在v-list-tile-title标记中显示它。我尝试了所有用到的承诺,但都行不通,也许您可​​以帮助我。对es6 tho不熟悉。

  <v-list-tile>
                        <v-list-tile-content>
                            <v-list-tile-title>{{ geocodedCoordinates address here }}</v-list-tile-title>
                            <v-list-tile-sub-title>{{ address.address }}</v-list-tile-sub-title>
                        </v-list-tile-content>
                    </v-list-tile>

1 个答案:

答案 0 :(得分:0)

根据您希望geocodelatLng()返回提供地理编码结果的承诺的信息,首先需要将geocoder.geocode()从回调API转换为Promises的内容。 here广泛涵盖了这样做的一般原则。

根据该建议,您可能会得到如下结果:

function geocodelatLng() {
    var response = [ ....... ]; // as in the question
    var promises = response.map(function(coords) { // map response to an array of Promises.
        return new Promise(function(resolve, reject) {
            var geocoder = new google.maps.Geocoder();
            var latLng = {
                'lat': parseFloat(coords.lat),
                'lng': parseFloat(coords.lng)
            };
            geocoder.geocode({'location': latLng}, function(results, status) {
                if (status === 'OK') {
                    if (results.length) {
                        resolve(results[0]); // or `resolve(results)` to deliver all results
                    } else {
                        reject(new Error('No results found'));
                    }
                } else {
                    reject(new Error('Geocoder failed due to: ' + status));
                }
            });
        });
    });
    return Promise.all(promises);
}

您可能会遇到以下问题:如果Promise.all()中的任何一个被拒绝,promises都会返回被拒绝的承诺,这可能是您不希望的。最好忽略拒绝(错误)并传递成功的结果。

herereflect函数的形式提供了针对该问题的解决方案,该函数可以如下应用:

function geocodelatLng() {
    var response = [ ....... ]; // as in the question
    function reflect(promise) {
        return promise.then(function(v) {
            return { 'status':'resolved', 'value':value };
        }, function(e) {
            return { 'status':'rejected', 'error':e };
        });
    }
    var promises = response.map(coords => { // map response to an array of Promises.
        return new Promise(function(resolve, reject) {
            var geocoder = new google.maps.Geocoder();
            var latLng = {
                'lat': parseFloat(coords.lat),
                'lng': parseFloat(coords.lng)
            };
            geocoder.geocode({'location': latLng}, function(results, status) {
                if (status === 'OK') {
                    if (results[0]) {
                        resolve(results[0]);
                    } else {
                        reject(new Error('No results found'));
                    }
                } else {
                    reject(new Error('Geocoder failed due to: ' + status));
                }
            });
        });
    });
    return Promise.all(promises.map(reflect)) // map `promises` to an array of "refelected" promises before passing to Promise.all()
    .then(function(results) {
        return results.filter(function(res) { // filter the reflected results to exclude errors
            return res.status === 'resolved';
        }).map(function(res) { // map the remaining reflected results to the value of interest
            return res.value;
        });
    });
}

geocodelatLng的调用方现在返回了一个Promise,它将(通过.then())传递所有成功的地理编码结果,这些结果可以传递给vuetify或其他任何形式。