Time for action – getting geolocation data

In this section we will add some code to our weather widget example to access the Geolocation API. You can find the code for this section in chapter8/example8.3.

First let's go into weather.html and add a section to show the user's location next to the Check Weather button:

<div id="controls">
    <div>
        Latitude: <input id="latitude" type="text"/><br/>
        Longitude: <input id="longitude" type="text"/>
    </div>
    <button id="getWeather">Check Weather</button>
    <div class="error">
        Error: <span></span>
    </div>
</div>

We add a <div> element with text fields to show the user's latitude and longitude that we got from the Geolocation API. We also add a <div class="error"> element to show the error message if geolocation fails.

Now let's go into weather.js and add some code to the WeatherApp object. We will add a getLocation() method:

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(
        function(position)
        {
            $("#latitude").val(position.coords.latitude);
            $("#longitude").val(position.coords.longitude);
        },
        function(error)
        {
            $("#controls .error")
                .text("ERROR: " + error.message)
                .slideDown();
        });
    }
}

First we check that the Geolocation API is available by checking that the geolocation object exists in the navigation object. Then we call geolocation.getCurrentPosition(). The callback function takes the position object and gets the latitude and longitude from its coords object. It then sets the latitude and longitude into the text fields:

Time for action – getting geolocation data

If the geolocation request failed for some reason, we get the error message from the error object and show it on the page:

Time for action – getting geolocation data

What just happened?

We used the Geolocation API to get the user's position. We extracted the latitude and longitude and displayed them in text fields on the page. We will pass this into the weather service to get the weather for their location.

Have a go hero

Create a web application that tracks the user's position using the Geolocation API. When the user's location changes, use Ajax to call the Google Static Maps API to get a map of the user's current position and update an image on the page. Open the application in your smart phone and drive around to see if it works. You can find the documentation for Google's Static Maps API at https://developers.google.com/maps/documentation/staticmaps/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.201