HTML5 Geolocation

published on December 13, 2011 in technical

I am currently planning an experimental social network, where I needed geolocation. This way I came across this client side possibility, here is a simple example of it.

1. The javascript

The actual code:

"use strict"

function getLocation() {
	if (navigator.geolocation) {
		console.log(navigator);
		navigator.geolocation.getCurrentPosition(function(position){
			try {
				document.getElementById("output").innerHTML =
					"Latitude: " + position.coords.latitude +
					"
Longitude: " + position.coords.longitude
			} catch (error) {
				document.getElementById("output").innerHTML = "Some error ocurred";
			}
		});
	} else {
		document.getElementById("output").innerHTML = "No geolocation support!";
	}
}

window.onload = function() {
	document.getElementById("click").onclick = getLocation;
}

On the click of a button I get the location of the user, specified by longitude and latitude.

2. Demonstration

I uploaded a working copy here, so everyone may see running in the browser.