HTML5 Geolocation Demo

  • Monday, January 17, 2011
  • Posted by filial23
  • Labels: ,

This is a demonstration of HTML5 Geolocation. Your location will be shown on Google Maps after your permission.






First I thought standard Geolocation APIs would work with all browsers including Safari and Firefox and Chrome, however it's impossible to get correct positional data from Chrome for Windows. I solved this problem by using Google Gears which requires to switch the code based on browser type as below.

var userAgent = window.navigator.userAgent.toLowerCase();
var chrome = (userAgent.indexOf("chrome") != -1) ? true : false;

Then get positional data correctly both Chrome and Firefox as below. If you are not familiar with the getCurrentPosition() method, please check the specification on W3C.org.

var geolocation = (chrome) ?
google.gears.factory.create('beta.geolocation') :
navigator.geolocation;

geolocation.getCurrentPosition(
successCallback,
errorCallback);

Finally get latitude and longitude according to what the browser type is, because these are not affordable via the coords object with Chrome, plot the client's position on Google Maps: I implemented PositionCallback and PositionErrorCallback as below.

function successCallback(p) {
var lat = (chrome) ? p.latitude : p.coords.latitude;
var lng = (chrome) ? p.longitude : p.coords.longitude;
var pos = new google.maps.LatLng(lat, lng);

var map = new google.maps.Map(document.getElementById("gmap"), {
zoom : 16,
center : pos,
mapTypeId : google.maps.MapTypeId.ROADMAP
});

var marker = new google.maps.Marker({
position : pos,
map : map
});
}

function errorCallback(err) {
document.getElementById("msg").innerHTML =
"Error using Geolocation API: " + error.message;
}


I've check if this program works with the latest version of Safari for Mac and Firefox and Chrome for Windows.
  • Safari - Sometimes it works unstably and often fails to get positional data on Mac. This problem can be solved by quitting Safari once. Probably there might be a few glitches in the code.
  • Firefox - It works with both Windows and Mac well.
  • Chrome - Google Gears For Mac is unavailable in this moment so that it doesn't work with Chrome for Mac.
WinMac
Safari×
Firefox
Chrome×
IE××


HTML5 Powered

0 comments:

Post a Comment