Ad

VueJS Set Input Field Data

- 1 answer

I want to set the value of an input field with VueJS, when I receive updated information from another function. I do not clearly understand, how to update the value of the input field when the function getLatLng returns. When I output on the console, it works very well, so the functions are working. But how do I connect my input field properly to show the Latitude value? Do I need a computed property? or just a regular one?

HTML

<form>
<input type="text" class="Form" placeholder="Latitude" v-model="latitude" value="@{{ latitude }}">
</form>

VUE

var Vue = require('vue');
import VueResource from 'vue-resource';
Vue.use(VueResource);

window.app = new Vue({
    el: '#GISContainer',

    // Data to be stored
    data: {
        // Save Data for address, latitude and longitude
        address: '',
        latitude: '',
        defaultMapLocation: 'Fichtenstrasse 30 82256',

        // Responder Information
        responders: [
            {id: 1, name: 'Test 1'},
            {id: 1, name: 'Test 2'},
        ]
    },
    // Methods
    methods: {
        init: function() {
            initGISMap(this.$els.map);
            this.address === '' ? setMapLocationToAddress(this.defaultMapLocation) : setMapLocationToAddress(this.address);
        },
        setMapToSearchAddress: function() {
            setMapLocationToAddress(this.address);
            getLatLng(this.address, function(latlng) {
                this.latitude = latlng[0];
            })
        }
    }
});

External JS Function

function geocodeAddress(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: address }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            if (results.length > 0) {
                callback(results[0].geometry.location);
            } else {
                console.log("No results found");
            }
        } else {
            console.log("Geocoder failed due to: " + status);
        }
    });
}

function getLatLng(address, callback) {
    latLng = [];
    geocodeAddress(address, function(position) {
        latLng.push(position.lat());
        latLng.push(position.lng());
        callback(latLng);
    });
}
Ad

Answer

To set the latitude you should bind the this keyword:

getLatLng(this.address, function(latlng) {
  this.latitude = latlng[0];
}.bind(this))
Ad
source: stackoverflow.com
Ad