HTML5 Geolocation API Tutorial with Example

html5-geolocation-api

HTML5 has finally pushed the web ahead with many new APIs that were lacking since the inception of HTML. New APIs like DOM Storage API helps in making better web applications.


As part of the specification, HTML5 added set of new APIs under title Geolocation that helps the applications to identify location related information from visiting users. Here is the official definition from HTML5 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. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device’s actual location.



The API can be used to get current location (latitude, longitude) of user.


Understanding Geolocation API


In order to utilize Geolocation API in a web application, we must understand the API structures. The browser that supports Geolocation API provides navigator object with geolocation object.This object can be used to retrieve location info. Following are the methods:



void getCurrentPosition(PositionCallback successCallback,
optional PositionErrorCallback errorCallback,
optional PositionOptions options);

This method takes a callback method successCallback which gets called once the location of user (browser) is determined. The geolocation object provides following useful methods to retrieve location related information.



interface Geolocation {
void getCurrentPosition(PositionCallback successCallback,
optional PositionErrorCallback errorCallback,
optional PositionOptions options);

long watchPosition(PositionCallback successCallback,
optional PositionErrorCallback errorCallback,
optional PositionOptions options);

void clearWatch(long watchId);
};

//watchPosition() method will register a handler which repeteadly
// gets called with current location details.

// callback PositionCallback = void (Position position);

// callback PositionErrorCallback = void (PositionError positionError);

Getting Current Location


Following is the simple example to retrieve current location of user’s browser. Note that your browser must support geolocation in order to run this example.


HTML Code


First we define a plain HTML, a button called “Show Location” and two spans to display latitude and longitude.



<html>
...

<input type="button" value="Show Location"
onclick="javascript:showlocation()" /> <br/>

Latitude: <span id="latitude"></span> <br/>

Longitude: <span id="longitude"></span>
...
</html>

JavaScript Code


In below javascript we defined a function showlocation() that gets called on click of “Show Location” button. This method registers a callback function called “callback” which does the work of displaying the latitude and longitude.



function showlocation() {
// One-shot position request.
navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {
document.getElementById('latitude').innerHTML = position.coords.latitude;
document.getElementById('longitude').innerHTML = position.coords.longitude;
}

Demo



Geolocation API and Google Maps integration


Let us quickly check a demo where we integrate HTML5 Geolocation API and Google Maps API. The idea is to fetch current location of user using Geolocation API and then showing it on map. Check out the demo first before we dig into the code.


Demo



Following is the complete code snippet. See how we adapted above code. The showlocation() method is called when the button is clicked. It initialize the Geolocation API using navigator.geolocation.getCurrentPosition() method. A callback method callback() is registered which gets called once the location is retrieved. In callback() method we fetch the latitude and longitude and set the Google map its center.



<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map = null;
function showlocation() {
// One-shot position request.
navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {

var lat = position.coords.latitude;
var lon = position.coords.longitude;

document.getElementById('latitude').innerHTML = lat;
document.getElementById('longitude').innerHTML = lon;

var latLong = new google.maps.LatLng(lat, lon);

var marker = new google.maps.Marker({
position: latLong
});

marker.setMap(map);
map.setZoom(8);
map.setCenter(marker.getPosition());
}

google.maps.event.addDomListener(window, 'load', initMap);
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);

}
</script>
</head>
<body>
<center>
<input type="button" value="Show my location on Map"
onclick="javascript:showlocation()" /> <br/>
</center>

Latitude: <span id="latitude"></span> <br/>
Longitude: <span id="longitude"></span>
<br/><br/>
<div id="map-canvas"/>
</body>
</html>

Error Handling


There are different error conditions that one should take care while dealing with Geolocation API. The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user’s location:



navigator.geolocation.getCurrentPosition(callback, errorHandler);

The errorHandler() method is called if there is any error while retrieving user location. This method will be called with one argument: error code. The error code should be checked for following values to know what type of error occurred.























Error codeMeaning
PERMISSION_DENIEDUser denied the request for Geolocation.
POSITION_UNAVAILABLELocation information is unavailable.
TIMEOUTThe request to get user location timed out.
UNKNOWN_ERRORAn unknown error occurred.

Source code



//..
navigator.geolocation.getCurrentPosition(callback, errorHandler);
//..

function errorHandler(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}

Get Current Location Repeatedly (Watching the location)


We saw how to get current user location using getCurrentPosition() method. However this method only gives location only once, when it is called. Sometimes it is desirable to get users location continuously if it changes. This will never happen if user is accessing webpage from a desktop machine. But smartphones/tablets are common contenders to use Geolocation API and get location continuously if user is on move.


The method watchPosition() is used to watch users location. Below is the syntax for this method:



long navigator.geolocation.watchPosition(callback);

The method takes one argument, the callback function which gets called when location is obtained. Note that unlike getCurrentPosition() method, the watchPosition() method returns a long value watchID. This id can be used to uniquely identify the requested position watcher; and this value can be used in tandem with the clearPosition() method to stop watching the user’s location.



navigator.geolocation.clearWatch(watchID);

Check out the demo below. You need to open this demo in device that has GPS built in. Otherwise this won’t work. Try openning this page in phone/tablet with GPS and move around. The latitude / longitude should change while you on move :)


Demo



Source code



<!DOCTYPE html>
<HTML>
<BODY>
Click Show location button and run :)
<input type="button" value="Show Location" onclick="showlocation()"/>

<br/>
Latitude: <span id="latitude">..</span> <br>
Longitude: <span id="longitude">..</span>

<SCRIPT>
function showlocation(){
navigator.geolocation.watchPosition(callback);
}
function callback(position){
document.getElementById('latitude').innerHTML=position.coords.latitude;
document.getElementById('longitude').innerHTML=position.coords.longitude;
}
</SCRIPT>
</HTML>

Browser compatibility


Like all other HTML5 APIs, the Geolocation API is also new in the town and not all browsers supports it. Following are the list of browsers with minimum version that have support for this API.

















ChromeFirefox (Gecko)Internet ExplorerOperaSafari
53.5 (1.9.1)910.60

Removed in 15.0

Reintroduced in 16.0
5

I hope this is useful. Let me know if you using HTML5 Geolocation API in some creative way. Would be interesting to know different usecases for this API :)








via ViralPatel.net http://feedproxy.google.com/~r/viralpatelnet/~3/brUFAA8OKv8/

No comments:

Post a Comment

If you have any question please let me know

[Software Update] Mozilla Firefox 125.0.1 Stable Released, Here is What’s New and Fixed

UPDATE: Release of Mozilla Firefox 125.0.1 stable version to public. Good news for Mozilla Firefox users! Mozilla has released Firefox 125.0...