Saturday, 14 April 2012

Tutorial: HTML5 Geolocation API

We can use HTML5 Geolocation API (Application Programming Interface) to provide information about current location of mobile devices such as iPhone, iPad, BlackBerry and Android phones. The API also include implementation for real-time tracking of devices's location.

With this particular API, we can create many innovative and useful location-based services and mobile apps such as ATM finders, cafe & restaurants locator or you can request a taxi from your current location.

User will be prompt with a pop-up message box asking their permission when you are using Geolocation API.



Remember that this API is only available for HTML5. Thus, you must declare at the very top of the HTML page.

Today, I am creating a simple page that use the HTML5 Geolocation API as below:



Below are working sample HTML5 code together with Geolocation API usage:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Geolocation API</title>
</head>
<body>
<img id="GoogleMap" />
<p id="locationInfo"></p>

<script>
var img = document.getElementById('GoogleMap');
var info = document.getElementById('locationInfo');

//The Geolocation API
navigator.geolocation.getCurrentPosition(successGetPosition,failToGetLocation);

//Successfully get device's location
function successGetPosition(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var timeStamp = new Date(position.timestamp);
// Display GPS info
info.innerHTML = 'Latitude:  '+latitude+'<br />'+
                'Longitude:  '+longitude+'<br />'+
'Timestamp:  '+timeStamp+'<br />';
 
// Display Google Map
img.src = "http://maps.google.com/maps/api/staticmap?sensor=true&"+
          "center="+latitude+","+longitude+"&zoom=13&size=295x295&markers=color:green|"+latitude+","+longitude;
}

// Function to handle error to get GPS info
function failToGetLocation(error){
var displayTxt;
switch(error.code){
case error.PERMISSION_DENIED:
displayTxt = 'Permission denied'; break;
case error.POSITION_UNAVAILABLE:
displayTxt = 'Position unavailable'; break;
case error.TIMEOUT:
displayTxt = 'Position lookup timeout. Please try again later.'; break;
default: displayTxt = 'Unknown position';
}
info.innerHTML = displayTxt;
}
</script>
</body>
</html>

PS: Happy geotagging!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...