Geolocation API, or Web-GL as it is sometimes referred to, is a W3C candidate recommendation for a method of informing a website of the user’s geographical location associated with the hosting device, primarily referencing the latitude and longitude position. Common sources of location information include:
- Global Positioning System (GPS)
- locations inferred from network signals such as an IP address, RFID, Wi-Fi and Bluetooth MAC addresses
- GSM/CDMA cell IDs
- user input
However, there is no guarantee that the API will return the device’s actual location; there is a margin for error, and in some cases the general location will be discovered. The API is designed to enable both “one-shot” position requests and repeated position updates, as well as the ability to explicitly query any cached positions. With Geolocation-enabled web pages, you can put a world of possibilities at your users’ fingertips. For an example, think of a web application that locates restaurants within a 5 mile radius of the user’s device location, a feature quite similar to many GPS devices today.
This feature can be implemented using Google’s IP-GeoCoding service as a fallback mechanism with the geolocation shim, which is available on Github. While Google’s geo-location JavaScript does not work as a fallback, it does provide ways to connect into BlackBerry, WebOS, and Google Gears specific APIs for mobile applications. In this piece, I will demonstrate using a simple location script based on the W3C Geolocation API.
Currently the W3C geolocation API is supported in the following browsers with fallback support as referenced at “When I can use Geolocation“: IE 9.0+, Firefox 3.5+, Chrome 5.0+, Safari 5.0+, Opera 10.6+, iOS Safari 3.2+, Opera Mobile 11.0+, and Android/Browser 2.1+/3.0+. A recent survey of global user statistics exhibit a 68.21% support rate based on the January 2012 StatCounter from Global Stats.
Scripts
The specification defines three methods in which the location information can be retrieved using JavaScript object calls with navigator.geolocation: the single shot position request, the repeated position request as the current position changes, and requesting or refreshing cached positions.
Single shot position request example code snippet:
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);
Repeated position requests example code snippet:
function scrollMap(position) {
// Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
}
// Request repeated updates.
var watchId = navigator.geolocation.watchPosition(scrollMap);
function buttonClickHandler() {
// Cancel the updates when the user clicks a button.
navigator.geolocation.clearWatch(watchId);
}
Repeated position updates and error handling example code snippet:
function scrollMap(position) {
// Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
}
function handleError(error) {
// Update a div element with error.message.
}
// Request repeated updates.
var watchId = navigator.geolocation.watchPosition(scrollMap, handleError);
function buttonClickHandler() {
// Cancel the updates when the user clicks a button.
navigator.geolocation.clearWatch(watchId);
}
Potentially cached position requests example code snippets:
// Request a position. We accept positions whose age is not
// greater than 10 minutes. If the user agent does not have a
// fresh enough cached position object, it will automatically
// acquire a new one.
navigator.geolocation.getCurrentPosition(successCallback,
errorCallback,
{maximumAge:600000});
function successCallback(position) {
// By using the 'maximumAge' option above, the position
// object is guaranteed to be at most 10 minutes old.
}
function errorCallback(error) {
// Update a div element with error.message.
}
Security
The Geolocation API also provides a level of user security and privacy considerations since, in most cases, the information discloses the location of the user of the device. Implementations that conform to the specification must provide a method that protects the user’s privacy, and this procedure should ensure that no location information is made available through the API without the user’s explicit permission.
Whenever you may access a web page that includes the Geolocation API code, a small notification will appear at the top of the page asking whether you want to share your location information with the application or not. Accessing the Dev Opera Geolocation API, results in the display in Figure B in Google Chrome 16. Browsers which support Geolocation have their own security notification, which permits the user to allow or deny the browser any access to the devices location.
Code example
The JavaScript to obtain the basic coordinate positions is placed within the <head> of the web page document:
<!-- Basic Geolocation script -->
<script type="application/javascript" >
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
alert('It appears that Geolocation, which is required for this web page application, is not enabled in your browser. Please use a browser which supports the Geolocation API.');
}
function successFunction(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
alert('Your location coordinates are: Latitude:'+lat+' Longitude: '+long);
}
function errorFunction(position) {
alert('Error!');
}
</script>
The script above was applied to a sample web page, and then displayed in Firefox 8.0.1; notice that the Geolocation security notification in Figure C is slightly different than in the previous Google Chrome example above.
The security notification in Firefox as demonstrated in this example, allows the user to select from the drop-down “Share Location”, and the selections include Always Share, Never Share, or Not Now. Once the user approves the Geolocation script to run on their browser, the resulting coordinates will be displayed as shown in the example in Figure D:
Further Reading
If you wish to learn more about utilizing the Geolocation API and other online mapping tools such as Google Maps, several resources are listed here:
- HTML5 Please
- When Can I use Geo Location
- Github Geo Location Shim Fallback
- Google Code Geo Location JavaScript
- W3C Specification
- Dev Opera Article
- Dev Opera Geolocation Example
A future post will review and demonstrate the Google Maps API script with web page documents, which create maps to display the user’s device location, including several options such as hard coding the zoom level, specifying the map type, and enabling Geo Coding.