3 May 2011
Basic HTML and JavaScript.
Intermediate
The Geolocation API is one of the most simple but also one of the most powerful new related technologies to HTML5. It allows you to figure out where your users are and then provide them information about what's around them. And with the explosion of smartphones, nearly everyone carries a GPS with them that you can use as part of your HTML and JavaScript applications. You can download the complete code for the example discussed in this article above or view it here.
Note: You can follow the tutorial with any version of Dreamweaver or a text editor.
The first thing to understand about using the Geolocation API is that it can mean a few different things depending on the device you're calling the API from. For example, on a mobile device, which has a GPS chip built in, in most cases the Geolocation API will call the GPS chip directly through the browser so that you get the exact longitude and latitude coordinates from the GPS chip in the phone. In some cases, however—say if GPS is turned off, but the phone still has location enabled—the API will return an approximate latitude and longitude based on other data the phone has like cell-phone towers or WiFi hotspots in the area.
That second method is how Geolocation works on devices that don't have built-in GPS, like on a laptop, for example. Because of this, the Geolocation API can be different depending on the browser that you're using to access it. Chrome and Firefox, for example, use the Google location API which uses a bunch of data including IP address and nearby Wi-Fi hotspots to return a latitude and longitude.
The good news is that as a developer, the API doesn't really change much at all depending on how the location is being retrieved. You still get a latitude and longitude object and you even get a property that will show you how accurate the GPS reading is.
The Geolocation API is one of the simplest and most powerful APIs in HTML5. To get location from a user, simply check that geolocation is supported and then call getCurrentPosition() on the navigator object:
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
} else {
alert("Your browser or device doesn't support Geolocation");
}
That's the basic API. Note parameters in the above snippet: In this case both are the callback functions that will be called when there is a successful geolocation call or when something goes wrong.
Before I dissect the data that comes back when you make a call to the Geolocation API, it's probably a good idea to address privacy and permissions. The spec for the Geolocation API is very specific about making sure that the API requests the user's permission before doing anything. This happens in a number of ways depending on your device, but in general it will appear as a prompt whenever the getCurrentLocation function is called. Your users are the ones who have ultimate control over whether or not you'll be able to access their locations so it's important to be clear what you're requesting and why. Figure 1 shows an example of the dialog box users see when you request their locations:
If a user denies access, you'll get an error and your error callback function will be called. I'll show you how to how to deal with that below.
If your geolocation call is successful, you'll get back a geoposition object, which has a bunch of location-related information. The data is contained within the coords object of the event and you can retrieve the following properties:
latitudelongitudeaccuracyaltitudealtitudeAccuracyheadingspeedThe event also includes a timestamp object that provides the date and time of the GPS fix.
So to display the current location on the screen, in a successful callback function you can do something as simple as this:
function onGeoSuccess(event)
{
alert(event.coords.latitude + ', ' + event.coords.longitude);
}
And you can use any of the properties above if they're available. Not all devices will provide all of those properties, so if you're trying to use them and they aren't there, the browser or device you're on doesn't support them.
Sometimes you won't get a GPS fix for a number of reasons. If that happens, and you've specified an error function when you called getCurrentLocation , you'll get some information about what the problem is. The event that is returned is a PositionError event and it has two properties, a code and a message . Code is an integer which represents the error code and message is a human readable message that explains what the code is. You may encounter four different types of errors:
UNKNOWN_ERROR: The browser doesn't have an answer for what went wrong.PERMISSION_DENIED : This is when the user disallows you from accessing their locationPOSITION_UNAVAILABLE : If the GPS chip isn't able to get a fix or if the location service is unavailable for any reason.TIMEOUT : The GPS wasn't able to get a location in the time specified. This can be customized as you'll see below.So you can create an error function that provides some information as to what caused the geolocation call to fail.
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
You can also customize some of the properties of the request by using a PositionsObject and setting a few properties. That can then be passed along with the success and failure callbacks in the getCurrentPosition function.
The PositionsObject has three properties:
enableHighAccuracytimeoutmaximumAge enableHighAccuracy can force the geolocation API to only use the GPS satellites and not use Wi-Fi or a cell tower. timeout lets you specify the number of milliseconds before the API gives up trying to get a location, and maximumAge will cache the last known location in memory for a set number of milliseconds and will then use that data next time the API is called if it is less than the maximumAge .
getCurrentLocation is great if you want to grab the location of your user in that specific moment in time, but what do you do if you want more consistent updates? That's where you can use the watchLocation function instead. watchLocation takes the same parameters as getCurrentLocation but your success callback function will be called whenever the user's location changes. One thing to note is that you can't control how often the API will request the location because the device figures out the ideal time between API checks and returns the data accordingly.
When you use watchLocation it will return a number. That number is what you use to stop the API from continuing to request location data whenever it changes.
var watchID;
function getLocationConstant()
{
if(navigator.geolocation)
{
watchID = navigator.geolocation.watchPosition(onGeoSuccess,onGeoError);
} else {
alert("Your browser or device doesn't support Geolocation");
}
}
function stopGetLocation(event)
{
navigator.geolocation.clearWatch(watchID);
}
At this point you should have a good background on adding geolocation to your own HTML appliations. Definitely check out the rest of the HTML5 Developer Center for great ways to add additional features to your web applications.