I have been working with Vue for a couple of months now and I have run into an error I cannot comprehend. My data variables are "disappearing" between methods. I am working on an Laravel app that allows a user to enter an origin, destination and a number of waypoints, if the route is valid I then obtain the elevation data for that route . I use the Google Maps API to compute the route and I then compile an object containing the GPS co-ordinates which describe the length of the route.
I then use this object in a second method to retrieve the elevation data. The reason for the second method is that I call it form a second button.
<script>
import { loadedGoogleMapsAPI } from "./GoogleMapsApiLoader";
export default {
mounted() {
loadedGoogleMapsAPI.then(() => {
this.initMap();
});
},
data() {
return {
mapOptions: {},
map: null,
co_ords: {},
origin_input: null,
destination_input: null,
};
},
methods: {
initMap() {
this.mapOptions = {
zoom: 7,
center: { lat: -28.4792625, lng: 24.6727135 },
mapTypeId: "terrain"
};
this.map = new google.maps.Map(
document.getElementById("map"),
this.mapOptions
);
},
directions() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(this.map);
directionsService.route(
{
origin: this.origin_input,
destination: this.destination_input,
travelMode: "DRIVING"
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
\\Do some processing to get the GPS co-ords
this.co_ords = list_of_gps_data; \\Set the global variable equal to the object containing the lat & long data
console.log(this.co_ords); \\this displays perfectly
} else {
window.alert("Directions request failed due to " + status);
}
}
);
},
elevation() {
console.log(this.co_ords);
}
}
};
</script>
The output of the first console.log(this.co_ords)
:
0: Object { latitude: "-29.11462", longitude: "23.75092" }
1: Object { latitude: "-29.11449", longitude: "23.75119" }
2: Object { latitude: "-29.11433", longitude: "23.75146" }
3: Object { latitude: "-29.11419", longitude: "23.75165" }
4: Object { latitude: "-29.11407", longitude: "23.75179" }
The output of the console.log(this.co_ords)
in the second method:
__ob__: {…}
dep: Object { id: 12, subs: [] }
value: {…}
__ob__: {…}
dep: Object { id: 12, subs: [] }
value: Object { … }
vmCount: 0
If i use the Vue debugger for Firefox to view the variables, the debug window never updates the variable, the variable value remains null:
co_ords:Object (empty)
What am I doing wrong, where is the object disappearing to? I have spent hours trying to find it, I have read and reread the Vue documentation, the Laravel documentation, I have tried defining the variable with a different name, I cannot explain it.