Thursday, March 28, 2024

Web Developer Class: HTML5 Geolocation

Many websites can benefit from knowing exactly where the user accessing their site is from, enabling a more personalized local experience. HTML5’s geolocation functionality can help you do just that, as we show in this tutorial. A restaurant comparison service can help the user find restaurants near where they are currently located. The possibilities are limited only by your imagination!

Obtaining the Geolocation Data Using HTML5

To get the current position, use the getCurrentPosition API call shown in listing 1. The first parameter is the function that will be called when the location was successfully returned. The second parameter is the function that will be called if there is an error. The third parameter is an object containing the parameters for the GPS request.

  • enableHighAccuracy-If true, the device will use its most accurate method to get location information. If false, the device will use its fastest or lower power consumption method depending on the device.
  • Timeout-The amount of time in milliseconds to wait on the device to acquire location information excluding the amount of time it takes the user to grant the web page access to geolocation data.
  • maximumAge-The amount of time in milliseconds to accept a previously acquired location. 0 means that a new location must be acquired from the device.
navigator.geolocation.getCurrentPosition(
gotPosition,
errorGettingPosition,
{'enableHighAccuracy':true,'timeout':10000,'maximumAge':0});

Listing 1: Requesting geolocation data

If the user grants permission and geolocation data is acquired successfully, the success handler function defined in the first parameter will be called and will pass in a position object shown in listing 2. The position object contains position, altitude, accuracy, heading and speed information.

function gotPosition(pos)
{
var outputStr =
"latitude:"+ pos.coords.latitude +"<br>"+
"longitude:"+ pos.coords.longitude +"<br>"+
"accuracy:"+ pos.coords.accuracy +"<br>"+

"altitude:"+ pos.coords.altitude +"<br>"+
"altitudeAccuracy:"+ pos.coords.altitudeAccuracy +"<br>"+
"heading:"+ pos.coords.heading +"<br>"+
"speed:"+ pos.coords.speed +"";

document.getElementById("Output").innerHTML=outputStr;
}

Listing 2: Getting GPS Data.

If there is a problem acquiring geolocation information, the error function will be called with an error object passed as a parameter. The error object contains a code property that defines the basic type of error along with a message describing the error seen in listing 3.

function errorGettingPosition(err)
{
if(err.code==1)
{
alert("User denied geolocation.");
}
else if(err.code==2)
{
alert("Position unavailable.");
}
else if(err.code==3)
{
alert("Timeout expired.");
}
else
{
alert("ERROR:"+ err.message);
}
}

Listing 3. The error handler

Position and Position Accuracy

Different devices have different degrees of accuracy and it is important that your application be aware of the difference. A cell phone that has a GPS unit inside of it that is switched on is usually accurate within three meters. A cell phone without a GPS unit, with the GPS unit switched off to maximize battery, or at a location where the GPS can’t contact the GPS satellites will have to use cell tower triangulation to estimate the users location and is typically accurate within 3000 meters which is accurate enough to know what neighborhood the user is in but completely useless to tell them what building they are looking at.

If the user is accessing your site from a computer connected to a land-based broadband connection it can usually pinpoint the precise address by consulting a provider database and pinpointing the exact address from the DSL or cable provider.

To get the accuracy of the location information, you can query the accuracy property on the coords object. The accuracy property isn’t exact by any means but it will give your application a good sense as to whether or not you have a nearly precise position or a neighborhood.

Altitude and Altitude Accuracy

Most GPS enabled devices are capable of reporting altitude but non-GPS methods such as cell triangulation can not report altitude. Altitude is frequently overlooked, it could be used in a variety of innovate ways to enable games, help users track skydiving, mountain climbing, position in a skyscraper and more.

If the device does not support altitude information, the altitudeAccuracy property on the position object will be null.

Permission, Latency and Error Handling

The HTML 5 specification explicitly requires the user grant permission to any web page requesting geolocation information. This means the request for location might still error even if the code has already checked for browser support if the user declines to provide your application with access.

Geolocation is not instantaneous. It usually takes between 1 and 20 seconds depending on the GPS device being used and whether or not the device already has a lock on the current location.

As a result of both the requirement that the browser ask the user to grant geolocation permission and the GPS time lag, the request for geolocation information is an asynchronous call.

Tracking Movement

If the user is accessing your web page from a device that is capable of movement, you can use the watchPosition method in order to get periodic updates to the user’s location as they move. The watchPosition API works the same way that the getPosition function does except the maximumAge parameter will also define the frequency your success handler will be called to report a new location as seen in Listing 4.

var watchid = navigator.geolocation.watchPosition(
gotPosition,
errorGettingPosition,
{'enableHighAccuracy':true,'timeout':10000,'maximumAge':20000});

Listing 4. The watchPosition API in action.

Similar to setInterval/clearInterval, watchPosition returns an ID number that is used to track the instance of watchPosition that is running. To unsubscribe from watching the current position, call clearWatch passing in the watchid seen in Listing 5.

navigator.geolocation.clearWatch(watchid);

Listing 5. Clearing a GPS Watch.

Compatibility

The geolocation API is fully supported by most modern browsers and mobile phones including:

  • Android 2.0+
  • iPhone 3.0+
  • Blackberry 5.0+
  • Palm WebOS 2.0+
  • Firefox 3.5+
  • Chrome 5+

Notably absent are Microsoft’s offerings including Internet Explorer 9 and Windows Phone 7. Microsoft has not made a specific commitment regarding when their browsers will support the geolocation API.

Conclusion

The geolocation API provides a powerful addition to any developer’s toolkit that is well supported in smartphones and modern browsers. Many kinds of applications and games can enriched by adding automatic location information. The location API can be paired up with google maps, bing maps or proprietary geolocation data to provide compelling solutions.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured