HTML5 Geolocation

Geolocation

function getLocation(){
  if (navigator.geolocation) {
  	  navigator.geolocation.getCurrentPosition(success, error);
	  console.log('got position');
	} else {
	  error('not supported');
	}
}
function error(text){
	text = text || 'failed';
	console.log(text); 
 }
function success(location){
	 var lat = location.coords.latitude;
	 var long = location.coords.longitude;
	 var url = "http://maps.google.com/maps?q="+ lat+","+long; 
}
  • Chrome 4
  • Safari 5
  • Firefox 3.5
  • Opera 10.6
  • IE 9

Two Main Methods

getCurrentPosition(successCallback, errorCallback)
gets the user current location once
watchPosition(successCallback, errorCallback)
regularly keeps polling the user location

The Position Object

  • location.coords.latitude
  • location.coords.longitude
  • location.coords.altitude
  • location.coords.accuracy
  • location.coords.heading
  • location.coords.speed

Handling Errors

function error (err) {
  switch(err.code) {
  case 1:
	alert("No permission to use geolocation");
    break;

  case 2:
	alert("Sorry, but a problem happened while getting your location");
	break;

  case 3:
	alert("Sorry, this is taking too long...");
	break;
  }
}
PERMISSION_DENIED = 1 
POSITION_UNAVAILABLE = 2
TIMEOUT = 3
code 
message

Code Lab

Browse into your labs folder in the geolocation folder and edit index.html. This page contains a <div id="map_canvas"> (even though it is not a canvas) that will contain our google map and it also contains three empty JavaScript functions: The first one we call when the page has finished to load is getLocation(). Then the two other functions will be callback function when getting user location: successCallback(pos) and errorCallback(err)

  1. In the code, look for a // TODO 1. Here we want to get the user location in one line using the "one-time location" function
    • Pass the success and error callback to the function you are going to use
  2. Look for a // TODO 2. Here we are using the Google Map API to create a coordinate (using the google.maps.LatLng function)
    • This google.maps.LatLng function expects a latitude and a longitude as parameters. Use the Position object, pos, provided by the success callback to get those informations
  3. Look for a // TODO 3. Here we need to get the accuracy of the obtained position so we are going to be able to display that in the map
    • Replace xxxxxx by the accuracy you can get from the Position object, pos
  4. Finally, open the final index.html in Firefox 3.5+, Safari 5.0+, Chrome 5.0+ or Opera 10.6+
  5. Allow the page to get user location and you should get a marker on a map representing your user location
Try it out

Other JavaScript APIs

Next ➹