September 14, 2015 6:48 pm

Useful HTML5 Features, Part 7

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).Useful HTML5 Features

[wpdm_file id=149]DEMO

Geolocation API’s browser support

The Geolocation API has an excellent support so you may feel free to start using it today. 90.68% of Internet users globally have browsers that support it according to Can I Use.

It is supported in the following browsers:
1. IE 9+
2. Firefox 31+
3. Chrome 31+
4. Safari 7+
5. Opera 30+
6. iOS Safari 7.1+
7. Android 4.1+
8. Chrome for Android 42+

Every major browser supports it except Opera Mini.

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.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Get Your Local Weather</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <style>
        body {
            background-color: #000;
            color: #fff;
            margin: 0 auto;

        }
        p {
            font-size: 2em;
            font-family: cursive;

        }
        p:first-letter {
            color: crimson;
        }

        p span {
            background-color: #fff;
            color: #000;
            display: inline-block;
            padding: 5px;

        }
    </style>
</head>
<body>

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:

if ("geolocation" in navigator) {
            /* 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:

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:

function getWeather(lat,long) {
            $.get("http://api.openweathermap.org/data/2.5/weather?lat=" + lat +"&lon="+long + "&units=metric",function(data) {

                showWeather(data);
            })
        }

Finally, our showWeather method accepts the returned weather data and creates markup using parts of it:

function showWeather(weatherData) {
            var html = "";
            html += '<p>Showing the weather for: <span>' + weatherData.name + '</span>';
            html += "<p>Current Temperature: <span>" + weatherData.main.temp + "</span> degrees Celsius";
            html += "<p>Weather Condition: <span>" + weatherData.weather[0].description + "</span>";
            var sunrise = new Date(weatherData.sys.sunrise * 1000);
            sunrise = sunrise.getDate() + "/" +sunrise.getMonth() + "/" + sunrise.getFullYear() +
            " " +sunrise.getHours() + ":"+ sunrise.getMinutes()
            + ":" + sunrise.getSeconds();
            var sunset = new Date(weatherData.sys.sunset * 1000);
          sunset =  sunset.getDate() + "/" +sunset.getMonth() + "/" +
          sunset.getFullYear() + " " +sunset.getHours() + ":"+
          sunset.getMinutes() + ":" + sunset.getSeconds();

            html += "<p>Sunrise at: <span>" + sunrise + "</span>";
            html += "<p>Sunset at: <span>" +  sunset + "</span>";
            $("body").html(html);
        }

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.

Author Ivan Dimov

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


Tutorial Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *