chrisgrim
1 month ago
222
5
Vue

Checking for google maps places json data using if statement

Posted 1 month ago by chrisgrim

Hi, I am using google auto complete for my location entry form. I am able to get the data back from google but I am having an issue when I am trying to enter it into my data. Here is my data

data() {
            return {
                location:this.initializeEventObject(),
                center: { lat: 45.508, lng: -73.587 },
                markers: [],
                places: [],
                currentPlace: null,
            }
        },

        methods: {
            initializeEventObject() {
                return {
                    StreetAddress: '',
                    City: '',
                    State: '',
                    Country: '',
                    Zipcode: '',
                    HiddenLocation: '',
                    Lat: '',
                    Long: '',
                }
            },

and after the user enters their info I call

setPlace(place) {   
                    this.location = {
                        StreetAddress: place.address_components[0].long_name + ' ' + place.address_components[1].long_name,
                        City: place.address_components[3].long_name,
                        State: place.address_components[4].long_name,
                        Country: place.address_components[5].long_name,
                        Zipcode: place.address_components[6].long_name,
                        HiddenLocation: '',
                        Lat: place.geometry.location.lat(),
                        Long: place.geometry.location.lng(),
                    }
            },

This works great except if the user doesn't enter a street, instead only adds a city then I get this error

app.js:41532 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'long_name' of undefined"

found in

I tried to do this

if (place.address_components[0].long_name) {
                    this.location = {
                        StreetAddress: place.address_components[0].long_name + ' ' + place.address_components[1].long_name,
                        City: place.address_components[3].long_name,
                        State: place.address_components[4].long_name,
                        Country: place.address_components[5].long_name,
                        Zipcode: place.address_components[6].long_name,
                        HiddenLocation: '',
                        Lat: place.geometry.location.lat(),
                        Long: place.geometry.location.lng(),
                    }
                };

but I am still getting the error. I also have another issue that sometimes place.address_components[5] is Los Angeles or sometimes its Los Angeles County. Is there a better way to uniform the response instead of just using [number]?

Thanks!

Please sign in or create an account to participate in this conversation.