Update form input value

Hello,

i have a input field for a location with google places autocomplete.
if somebody inputs only a postal code, the component tries to get the address and lat/lon values.
Calculating the address is working, but i can not make the input field to update again. Once the user leaves the input field, the correct address should be inserted (if address is possible to calculate)

The form field:

          <input ref="autocomplete"
                       v-model="locationResult"
                       name="location"
                       placeholder="Example: London"
                       class="form-control "
                       onfocus="value = ''"
                       v-on:blur="checkLocationInput()"
                       type="text" />

Defining data:

        data() {
            return {
                autocomplete: '',
                locationResult: '',
                latResult: '',
                lngResult: ''
            };
        },

Getting the address by postal code (at least try) and updating the input value.
Why is “this.locationResult = …” not changing the visible value of the input field?

 methods: {
            checkLocationInput(){
                //check
                if (/^\d{5}$/g.test(this.locationResult)) {
                    let geocoder = new google.maps.Geocoder();

                    geocoder.geocode({'address': this.locationResult + ", United Kingdom"}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            this.locationResult = results[0].formatted_address;
                            
                            this.latResult = results[0].geometry.location.lat();
                            this.lngResult = results[0].geometry.location.lng();
         
                        }
                    });

                }
            },

Anybody who knows how to solve this? Thank you

Hi

this inside the callback function to geocoder.geocode isn’t pointing to the component. Either use a simple function as callback (which preserves the this inside the function:

geocoder.geocode({'address': this.locationResult + ", United Kingdom"},(results, status) => {
                        if (status == google.maps.GeocoderStatus.OK) {

or define let that = this (you could name it anything you like but that is often used for this purpose) before the callback and then do

that.locationResult = results[0].formatted_address;

That does the trick, thank you!

1 Like