HTML5 Series – Location

Being able to get a users location opens up some great functionality especially when used on mobile devices that could be anywhere. HTML5 makes it really easy to capture the users latitude and longitude in just a couple of lines of JavaScript.

What’s important to remember though is the user always has the option of denying your request for their location so error handling is very important.

First you need to check to see if the device actually support geolocation by doing navigator.geolocation

            if (navigator.geolocation) {
                // success code to go here
            } else {
                alert("location not supported");
            }

Next we need to call navigator.geolocation.getCurrentPosition to get the current location. As capturing a location isn’t something that happens instantly (first the browser will check with the user that this is ok and then it may take a few seconds for the device to actually work out the location) you need to provide a function that will be called when the location has been established.

After that accessing the location is easy just look at the coords.latitude and cords.longitude properties on the object that was returned to your callback function.

    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (location) {
                    document.getElementById("latitude").innerText = location.coords.latitude;
                    document.getElementById("longitude").innerText = location.coords.longitude;
                }, function (error) {
                    alert(error.code);
                });
            } else {
                alert("location not supported");
            }
        }
    </script>


    Latitude: <span id="latitude"></span>
    Logitude: <span id="longitude"></span>

    <button onclick="getLocation();">Get location</button>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s