A Simple Example

Contact Us or call 1-877-932-8228
A Simple Example

A Simple Example

Let's look at a simple page (GeoLocationAPI/Demos/findmylocation.html) that pops up a JavaScript message with the user's latitude and longitude location. Users who visit our page will be prompted to explicitly allow our page to use their current location; see the left screenshot below. If they accept, our page will respond with their latitude and longitude, as on the right.

two iphone screenshots - geolocation example

Code Sample:

if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
	function locateSuccess(loc) {
		var latitude = loc.coords.latitude;
		var longitude = loc.coords.longitude;
		alert('You are at ' + latitude + ', ' + longitude);
	function locateFail(geoPositionError) {
		switch (geoPositionError.code) {
			case 0: // UNKNOWN_ERROR
				alert('An unknown error occurred, sorry');
				alert('Permission to use Geolocation was denied');
				alert('Couldn\'t find you...');
			case 3: // TIMEOUT
				alert('The Geolocation request took too long and timed out');

We test, with an if statement, for the presence of the navigator.geolocation object; if so, we call the getCurrentPosition function. We write two functions, locateSuccess and locateFail, to handle the success and failure cases, respectively.

On successful finding of the user's location, function locateSuccess is invoked. Note that, as discussed above, we can name this function anything we like (though, of course, a meaningful name containing "success" makes sense here), as long as the name of the function is the same name we use for the first parameter of the getCurrentPosition function. The loc parameter exposes a variety of information about the user's location; we assign loc.coords.latitude and loc.coords.longitude to two local variables, and show those values to the user in a JavaScript alert (popup) window.

If the user's location is not found, function locateFail is invoked. We use a JavaScript switch statement to evaluate parameter geoPositionError's code property: if 0, something unknown happened; if 1, the user denied permission; etc.

Of course, we could extend this application extensively: we might use Google's Places library to allow the user to perform a search for "Jazz Clubs" and to return human-friendly addresses (rather than latitude and longitude). Check out the Google Maps Demo Gallery for some inspiration and code samples.

The parameter passed to the success function, which we named loc in our example above, exposes a useful set of properties:

Position Properties
Property Units
coords.latitude degrees
coords.longitude degrees
coords.altitude meters (may be null)
coords.accuracy meters
coords.altitudeAccuracy meters (may be null)
coords.heading degrees clockwise (may be null)
coords.speed meters/second (may be null)
timestamp a date and time