[Vuejs]-How to reverse geocode properly with vue2-google-maps

3👍

geocodedAddress is async, you can’t use it in HTML template.

You should create a data attribute (for example formatedAddresses) to store result from async request

 data() {
     return {
         locations: [],
         formatedAddresses: []
     }
 },
 created() {
     // for example, you can call it in created hooks
     this.geocodedAddress()
 },
 methods: {
    geocodedAddress() {
        var self = this;
        let geocoder = new google.maps.Geocoder();
        let theLocations = this.locations ;

        return Promise.all(_.map(theLocations, addr => { 

        var geocoder = new google.maps.Geocoder();

            var locationss = { 
                lat : parseFloat(addr.lat),
                lng : parseFloat(addr.lng)
            } ; 

            // var sampleLocation = { lat: 1.39, lng: 103.8 };

            return new Promise(function(resolve, reject) {
                geocoder.geocode({'location': locationss }, function(results, status){
                    if (status === 'OK') {
                    if (results[0]) {
                        return results[0].formatted_address;
                    } else {
                        console.log(status);
                        window.alert('No results found');
                        return null
                    }
                    }
                })
            });
        })).then(data => {
            console.log(data)
            this.formatedAddresses = data
        })
    }
}

and in template

  <div v-for="address in formatedAddresses" :key="address">{{ address }}</div>
👤ittus

Leave a comment