HTML5 Geolocation - Locate a user's position


// Does the browser support geolocation?
// @see http://www.w3schools.com/html/html5_geolocation.asp.
if(navigator.geolocation) {
	// When clicked on deny, error function is triggered.
	navigator.geolocation.getCurrentPosition(success,error);
} else {
	console.log('Browser doesn\'t support geolocation, default geolocation unsupported action.');
}

function success(pos) {
	console.log('User allows, location specific action.');
}
function error(error) {
	console.log('User denies, default geolocation supported action.');
}

Load a static map based on the user's current position


/**
 * Act on a successfull position locator. 
 */
function success(pos) {
	  var crds = pos.coords;
	  var image = "http://maps.googleapis.com/maps/api/staticmap?center="
	  + crds.latitude + ',' + crds.longitude + "&zoom=14&size=400x300&sensor=false";
	  document.getElementById("map").innerHTML = "";
}

Act on geolocation failure


/**
 * Act on failed position locator.
 * Failure can have different reasons,
 * mainly, it is the user denying geolocation.
 */
function error(error) {

  	switch(error.code) {
    	case error.PERMISSION_DENIED:
  		  	console.log("User denied the request for Geolocation.");
  		  	break;
  	  	case error.POSITION_UNAVAILABLE:
  		  	console.log("Location information is unavailable.");
  		  	break;
  	 	case error.TIMEOUT:
  		  	console.log("The request to get user location timed out.");
  		 	 break;
  	 	case error.UNKNOWN_ERROR:
  		  	console.log("An unknown error occurred.");
  		  	break;
    }
  	var image = "http://maps.googleapis.com/maps/api/staticmap?center=0,0&zoom=1&size=400x300&sensor=false";
	document.getElementById("map").innerHTML="";
	
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.