In this article, we are going to build a simple app that receives the user’s geographic coordinates (latitude and longitude) with the HTML5’s Geolocation API and shows the current weather for the place they are located in (using a remote API provided by OpenWeatherMap).

About Gelocation

Before we start, it is important to know that the user has to allow geolocation usage for your website before you can use his location. If the user does not allow your website to get his coordinates – then you would not be able to use this feature.

Getting the current local weather with the Geolocation API

Our skeleton just loads jQuery and adds some basic styles to the text with the local weather (which will be added with JavaScript. Therefore, if the user does not allow the website to use his location – he will get a blank screen).

We declare our paragraphs to have a white color with a cursive font and be bigger than usual. Then, we add some emphasis to the span tag which will hold the weather values retrieved from the weather API.

If the user supports/has enabled geolocation ( "geolocation" in navigator is true) then we get the weather by calling our getWeather function and pass it the latitude and longitude from the Geolocation API.

The syntax is the following:

1

2

3

4

5

6

if("geolocation"innavigator){

/* geolocation is available */

navigator.geolocation.getCurrentPosition(function(position){

getWeather(position.coords.latitude,position.coords.longitude);

});

}

Otherwise, we give the user a friendly alert instructing him what to do:

1

2

3

4

else{

/* geolocation IS NOT available */

alert("To see the weather for your location please enable geolocation");

}

Next is our getWeather function which just performs a XHR GET request to the OpenWeatherMap API and calls showWeather when the results are ready:

Notice that we are converting the sunrise/sunset times from a UNIX timestamp to a date string in the format that we want.

Conclusion

Geolocation can be the source of powerful applications. Many applications out there are already using it. With it, you can create dating sites that finds people in the area, show the weather for the user’s location in your website (as you just saw), create apps that recommend people sights to visit in their area and an endless more groups of things.

I encourage you to go on and build something cool with the Geolocation API and tell me all about it in the comments below.

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter