Vue

Weather App - Using geolocation and Vue

Get the weather data from the user location

Table of Contents
  1. Geolocation
  2. VueJs
    1. Methods for the geolocation
  3. Conclusion

In this post, I will be using the same files as my previous tutorial - Creating a weather app: using Vue and Axios - because what I will show you is tightly tied to the previous tutorial.

You might be wondering, why I am writing this post.

The previous tutorial was an introduction to Vue and Axios, but the location was hardcoded in the Vue app. If you want a working weather app you will only be able to get the weather in London and not your city.

Do you need to read the previous tutorial to follow this one?

No. You can just get the needed files and start where we left off. You will also need to get an API key from OpenWeatherMap so you can get the weather information.

Geolocation

HTML5 offers a Geolocation API so you can get the location of a user - in this case, you. Geolocation is also available on 93% of the browsers according to Can I use, which means that most browsers support this function.

When using geolocation you need to know a few things:

  • The user needs to approve the request to share the location
  • Geolocation is more accurate for devices with GPS
  • Geolocation API will only work on secure contexts such as HTTP (some browsers won't ask for the permission and get decline straight away).

Because geolocation is dependent on the user accepting to share the location, we should have a strategy when our app can't get the location.

A final thing worth to mention. I have tried a few ways to make geolocation work with Vue. A lot of them failed, but in the end, I was able to make it work by creating a function to check if geolocation is enabled. If it was, then a new function would be called and we would get the latitude and longitude details.

VueJs

Our VueJs app was left in this state:

js
1let weatherApp = new Vue({
2 el: '#app',
3 data: {
4 currentTemp: '',
5 minTemp: '',
6 maxTemp:'',
7 sunrise: '',
8 sunset: '',
9 pressure: '',
10 humidity: '',
11 wind: '',
12 overcast: '',
13 icon: ''
14 },
15 methods: {
16 getWeather() {
17 let url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&APPID={Your API Key}";
18 axios
19 .get(url)
20 .then(response => {
21 this.currentTemp = response.data.main.temp;
22 this.minTemp = response.data.main.temp_min;
23 this.maxTemp = response.data.main.temp_max;
24 this.pressure = response.data.main.pressure;
25 this.humidity = response.data.main.humidity + '%';
26 this.wind = response.data.wind.speed + 'm/s';
27 this.overcast = response.data.weather[0].description;
28 this.icon = "images/" + response.data.weather[0].icon.slice(0, 2) + ".svg";
29 this.sunrise = new Date(response.data.sys.sunrise*1000).toLocaleTimeString("en-GB").slice(0,4);
30 this.sunset = new Date(response.data.sys.sunset*1000).toLocaleTimeString("en-GB").slice(0,4);
31 })
32 .catch(error => {
33 console.log(error);
34 });
35 },
36 },
37 beforeMount() {
38 this.getWeather();
39 },
40});

Immediately, we can see that the method getWeather will need to be refactored because the API URL is hardcoded to display the weather in London only. The rest of the function seems to be pretty good since we are just assigning values obtained from the API. If we change the URL bit everything will stay the same.

js
1getWeather(url) {
2 axios
3 .get(url)
4 .then(response => {
5 this.currentTemp = response.data.main.temp;
6 this.minTemp = response.data.main.temp_min;
7 this.maxTemp = response.data.main.temp_max;
8 this.pressure = response.data.main.pressure;
9 this.humidity = response.data.main.humidity + '%';
10 this.wind = response.data.wind.speed + 'm/s';
11 this.overcast = response.data.weather[0].description;
12 this.icon = "images/" + response.data.weather[0].icon.slice(0, 2) + ".svg";
13 this.sunrise = new Date(response.data.sys.sunrise*1000).toLocaleTimeString("en-GB").slice(0,4);
14 this.sunset = new Date(response.data.sys.sunset*1000).toLocaleTimeString("en-GB").slice(0,4);
15 })
16 .catch(error => {
17 console.log(error);
18 });
19 },

The variable URL was deleted and we are simply adding a parameter url to the getWeather function. Now, we can get our hands into creating methods for the geolocation and getting the URL.

First, we will add two constant variables to the top of our main.js file(lines 1 and 2):

js
1const API = 'http://api.openweathermap.org/data/2.5/weather?units=metric'
2const KEY = '&APPID={Your API Key Here}'

Now inside the VueJs app we will create two methods:

  • geolocation()
  • buildUrl(position)

As I said before, geolocation needs to have a function as a parameter if we want to do something with the latitude and longitude obtained through the browser. The method buildUrl(position) is just that, the position parameter will be used to extract these two things.

Methods for the geolocation

The methods will be quite simple to understand, first, we will call the getCurrentPosition method from the Geolocation API. The two parameters passed are callback functions - one if it was successful(this.buildUrl) and one if an error was returned(this.geoError).

js
1geolocation() {
2 navigator.geolocation.getCurrentPosition(this.buildUrl, this.geoError);
3 },
4 buildUrl(position) {
5 const lat = position.coords.latitude;
6 const lon = position.coords.longitude;
7
8 this.getWeather(API + '&lat=' + lat + '&lon=' + lon + KEY);
9 },
10 geoError(error) {
11 this.getWeather(API + '&lat=0&lon=0' + KEY);
12 }

As you can see the methods are pretty straightforward, we are simply building the API URL depending on how successful it was to get the user location, if not then we will just use 0,0 as location. Bonus points if you figure out where it is.

One final change we need to do to the VueJs app is replacing the method being called on beforeMount(). Instead of calling this.getWeather() we need to call this.geolocation().

Our main.js file will look like this:

js
1const API = 'http://api.openweathermap.org/data/2.5/weather?units=metric'
2const KEY = '&APPID=9ef28fe3735a820928decffcf48f5c3f'
3
4let weatherApp = new Vue({
5 el: '#app',
6 data: {
7 currentTemp: '',
8 minTemp: '',
9 maxTemp:'',
10 sunrise: '',
11 sunset: '',
12 pressure: '',
13 humidity: '',
14 wind: '',
15 overcast: '',
16 icon: '',
17 location: ''
18 },
19 methods: {
20 getWeather(url) {
21 axios
22 .get(url)
23 .then(response => {
24 this.currentTemp = response.data.main.temp;
25 this.minTemp = response.data.main.temp_min;
26 this.maxTemp = response.data.main.temp_max;
27 this.pressure = response.data.main.pressure;
28 this.humidity = response.data.main.humidity + '%';
29 this.wind = response.data.wind.speed + 'm/s';
30 this.overcast = response.data.weather[0].description;
31 this.icon = "images/" + response.data.weather[0].icon.slice(0, 2) + ".svg";
32 this.sunrise = new Date(response.data.sys.sunrise*1000).toLocaleTimeString("en-GB").slice(0,5);
33 this.sunset = new Date(response.data.sys.sunset*1000).toLocaleTimeString("en-GB").slice(0,5);
34 })
35 .catch(error => {
36 console.log(error);
37 });
38 },
39 geolocation() {
40 navigator.geolocation.getCurrentPosition(this.buildUrl, this.geoError);
41 },
42 buildUrl(position) {
43 const lat = position.coords.latitude;
44 const lon = position.coords.longitude;
45
46 this.getWeather(API + '&lat=' + lat + '&lon=' + lon + KEY);
47 },
48 geoError(error) {
49 this.getWeather(API + '&lat=0&lon=0' + KEY);
50 }
51 },
52 beforeMount() {
53 this.geolocation();
54 },
55});

Conclusion

This is a very brief tutorial on how to use the Geolocation API with VueJs. The reason why I decided to write this tutorial was because I had plenty of issues trying to make it work on my Quote and Weather landing page so hopefully, this will help you in case you are stuck.

Finally, we should probably change the app so it shows the current location in order for our users to know which weather data did they get. I will leave this challenge for you to complete - you might have to fix the CSS a bit as well if you add the location.

You can get the updated main.js file here.

Webmentions

0 Like 0 Comment

You might also like these

Using VueJs with Axios to connect to OpenWeatherMap API then we build a simple weather web application.

Read More
Vue

Creating a Weather App

Creating a Weather App

Exploration on how to run Pyscript in a React (NextJS) app, this article explores issues and solutions to run PyScript in a React app.

Read More
PyScript

How to run PyScript in React

How to run PyScript in React

How to create a function to filter articles by tag. On this post I am using the javascript filter method to filter all articles.

Read More
React

How to filter all MDX articles by tags

How to filter all MDX articles by tags

A quick introduction on how to use the Elasticlurn Plugin for Gatsby together with MDX to create a search bar component and allow users to search your site.

Read More
React

How to use elasticlunr plugin with MDX

How to use elasticlunr plugin with MDX