1 :: Geolocation

HTML5 + the Geolocation JavaScript API (WC3) allows access to the browser’s physical location – if the user allows it.

Here’s a demo from w3schools which features a demo that works for my iTouch (using Safari) and my laptop (using Firebox) but doesn’t seem to work from Chrome for my laptop – which really threw me because this feature is pretty much supported by every browser now – even IE.

[At this point I research online and I determine that it is an Ubuntu-Chromium error that should be resolved once Chromium is updated… which prompted me to update my laptop to to Ubuntu 12.10 to see if would change anything (it didn’t). This prompted me to change my default browser to Firefox which required more time setting it all up the way I like. In other words, several hours of yak shaving passed…]

The geolocation API in HTML5 requires latitude and longitude but in decimal form.

Normally, longitude and latitude are expressed as : degrees, minutes, and seconds. For example, Windsor, Ontario, Canada (where I live) is expressed as : N 42° 18′ 0” W 83° 1′ 1”

To express it as a decimal, you can run this function:

function degreesToDecimals (degrees, minutes, seconds) {
     return degrees + (minutes / 60.0) + (seconds / 3600.0);
}

This turns (N 42° 18′ 0” W 83° 1′ 1”) into (42.3, -83.017) — as longitude West and latitude South are represented by negative values. Using 6 digits after the decimal point gives around 1 meter accuracy (though this depends on where you are in the world).

Six

It is surprisingly easy to use geolocation. Here’s a code example from HeadFirst HTML5 which returns the text of one’s location with a little bit of html and a little bit of JavaScript:

<!-- myLoc.html -->
<!doctype html>
<html>
<head>
  <title>Where in the world are you?</title>
  <meta charset="utf-8">
  <script src="myLoc.js"></script>
</head>
<body>
  <div id="location">
     Your location will go here.
  </div>
</body>
</html>

/* myLoc.js */

window.onload = getMyLocation;

function getMyLocation() {
    if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(
            displayLocation) 
    }
    else {
        alert("Oops, no geolocation support");
    }
}

function displayLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var div = document.getElementById("location");
    div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}

For me, it returns: “You are at Latitude: 42.3210548, Longitude: -83.01374480000001”.

Where are you?

Leave a Reply

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