Introduction
Definition of the Geolocation API in the specification: "The Geolocation API
defines a high-level interface to location information associated only with the
device hosting the implementation, such as latitude and longitude." (technically
the Geolocation API is not a part of the HTML5 standard, instead it's actually a
separate specification)
The location information may be sourced from various points - such as Wifi, IP,
GPS, GSM/CDMA cell IDs etc.
The location information can then be used to further provide meaningful utility
to the user - such as getting directions, information on business or surrounding
area.
The Geolocation API requires the user's permission. Location information is
sensitive and the API needs to have the user's consent. This action could be
taken up by the browser in various forms - such as a question in the browser's
information bar or a pop up dialog. The user may be offered the choice to
remember his/her response from that point onwards.
As with other HTML5 features, you need to verify the support for the API in the
client browser. This can be done simply by testing for the existence of the
geolocation object.
API Methods
-
getCurrentPosition
The getCurrentPosition method is used for a one time query on the location.
-
watchPosition
The watchPosition method is used when location updates are also needed. When
you want to stop the continued updates for the position, you need to call
the clearWatch method, using the same watchID value. This is very useful
when you want to track changes such as direction mapping applications.
Both the methods are
asynchronous. The methods specify a mandatory successCallback argument and can
optionally specify an errorCallback function and options for the location
query. The various options that can be customized for the location query are :
enableHighAccuracy (precise location but may cause slower response and higher
power usage), timeout (default of zero which indicates no timeout) and
maximumAge (expiration for cached location).
In case there was an error, the error callback is invoked, if it was specified
in the getCurrentPosition/watchPosition method call. Typical error situations
are if the user has denied permission to access the location information, or the
position is unavailable, timeouts etc.
If the location was successfully retrieved, the success callback method is
invoked. Once you get the location, you can utilize it in your application.
The result location information is returned in a Position object. The Position
object has properties which can include expanded location information. Latitude,
longitude, altitude, accuracy, altitudeAccuracy, heading, speed and timestamp.
The Latitude, longitude and accuracy properties are populated whereas the
remaining properties may be populated if supported or may be null.
Code Sample
In this code sample, we will run a very basic script to get the user's location
and display the latitude and longitude in a text box. When the "Get my
Location" button is clicked, we check if the geolocation api is supported and if
it is supported, a call is made to the getCurrentPosition method of the
navigator object. The success callback method (displayResult) displays the
latitude and longitude retrieved for the user or in case an error occurred, the
error callback gets executed and the error message is displayed to the user.
Sample in Action: Here
are some screen shots of the application running in Mozilla Firefox 6.0.2
Figure: browser prompt for user's permission
Figure: Success - got the location!
Figure: Error
Source Code: save as
geo.htm (or a file name of your preference)
<!DOCTYPE HTML><html>
<body>
<script language="javascript">
function getUserLoc() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
displayResult,
displayError);
}
else {
setMessage("Geolocation is not supported by this browser");
}
}
function displayResult(position) {
setMessage("Latitude: " +
position.coords.latitude + ", Longitude: " +
position.coords.longitude);
}
function setMessage(msg) {
document.forms[0].myLoc.value = msg;
}
function displayError(error) {
var errors = { 1:
'Permission denied', 2:
'Position unavailable', 3:
'Request timeout' };
setMessage("Error occured: " +
errors[error.code]);
}
</script>
<form>
<input
type="button"
onClick="getUserLoc( );"
value="Get
my location"/>
<input
type="label"
name="myLoc"
size="200"/>
</form>
</body>
</html>
Conclusion
In this article, we took a look at the geolocation API. It's a
simplistic solution but opens up a universe of possibilities. An application
could tie in with a library such as the Google map APIs to provide elaborate
geography/mapping solutions.
Happy Coding!