I'm currently experimenting with axios to retrieve data from openweathermap. I've been working on constructing the URL by utilizing various methods to extract latitude and longitude from the user's browser, followed by a function call to piece together the URL.
Although the URL is constructed successfully without any hitches, when attempting to make the API call using axios, some strange occurrences transpire (essentially, I receive my own page's HTML code as the response).
Below is the code snippet:
let weather = new Vue ({
el: '#weather',
data: {
error: '',
apiUrl: '',
city: '',
country: '',
icon: '',
description: '',
results: [],
},
methods: {
getPosition: function() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(this.getUrl);
}else{
this.error = 'Geolocation is not supported.';
}
},
getUrl: function(position){
let lat = position.coords.latitude;
let lon = position.coords.longitude;
this.apiUrl = buildWeatherUrl(lat, lon);
},
getWeather: function(){
axios.get(this.apiUrl).then(function (response) {
this.city = response.data.name;
this.results = response.data;
}).catch( error => { console.log(error); });
}
},
beforeMount() {
this.getPosition();
},
mounted() {
this.getWeather();
}
});
Being new to both Vue and axios, I'm uncertain about where I may have gone wrong. I also attempted adding let self = this;
and substituting all instances of this
with self
in the getWeather
method, but that didn't yield any positive results.
The crux of the issue lies in trying to access the URL retrieved from apiUrl
, which should be updated by the getUrl
method. However, upon executing getWeather
post-mounting, the URL doesn't appear to be updated (it works seamlessly if hardcoded).
Thank you for any assistance provided.