HTML 5 – as-yet unreleased, but shaping up well – contains a specification for finding the current location of the user. The API, if your browser supports it and you grant the web application access, returns your latitude, longitude, elevation, speed and some other details. (If your web-capable device doesn’t have GPS, these details will be estimated using your IP address and other factors.)
A couple of weeks ago, I created a page to test this feature. If your browser is geo capable, this will reveal exactly what data about your location is being sent to web applications that ask for it.
If you’re a developer, here’s how I created the page.
Developing for geolocation in Javascript
The following all occurs in a Javascript code block towards the bottom of the page. You could also include this in the jQuery $() function, if you use that framework – the point is that it needs to execute once the page layout has been written to the browser.
Testing for geolocation capability
To test whether the browser has geolocation capabilities, we need to test for the existence of navigator.geolocation
:
if (navigator.geolocation) { // Execute geolocation code } else { // Execute code for geolocation not available }
Getting location data
The actual function to call in order to get the location data is: navigator.geolocation.getCurrentPosition(exportPosition, errorPosition);
Both exportPosition
and errorPosition
are functions that we must define. The former is called if the location is retrievable; the latter if it isn’t. (You can also omit the second parameter and neglect to have an error handler function.)
The exportPosition
function takes one parameter: position
. This in turn has a property, coords, which contains all of the major location data:
- position.coords.latitude: the latitude of the user
- position.coords.longitude: the longitude of the user
- position.coords.accuracy: a number representing the accuracy of the latitude and longitude (in metres)
- position.coords.altitude: the altitude of the user in metres above sea level
- position.coords.altitudeAccuracy: the accuracy of the above altitude reading, again in metres
- position.coords.heading: the heading of the user, in degrees clockwise from north
- position.coords.speed: the speed of the user in metres per second
This can then be fed into the functionality of your choice.
For an example of how this can be used, have a look at the source of my test page. Browsers that are known to support geolocation include:
- Firefox 3.5
- Safari in iPhone 3.0
Because geolocation is included in the HTML 5 specification, most browsers will support this soon.
Leave a Reply