Member Sign In
Not a member?

A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.


It's fast and free.

Webmonkey is a property of Wired Digital.
processing...
Join Webmonkey

Please send me occasional e-mail updates about new features and special offers from Wired/Webmonkey.
Yes No

Please send occasional e-mail offers from Wired/Webmonkey affiliated web sites and publications, and carefully selected companies.
Yes No

I understand and agree that registration on or use of this site constitutes agreement to Webmonkey's User Agreement and Privacy Policy.
Webmonkey is a property of Wired Digital.
processing...

Retrieve Sign In

Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.

or
Webmonkey is a property of Wired Digital.
processing...

Welcome to Webmonkey

A private profile page has been created for you.
As a member of Webmonkey, you can now:
  • edit articles
  • add to the code library
  • design and write a tutorial
  • comment on any Webmonkey article
Close
Webmonkey is a property of Wired Digital.

Sign In Information Sent

An e-mail has been sent to the e-mail address registered in this account.
If you cannot find it in your in-box, please check your bulk or junk folders.
Sign In
Webmonkey is a property of Wired Digital.

Track User Geolocation With JavaScript

/skill level/
/viewed/
0 Times

Location-based applications aren't just for mobile devices anymore. Now you can access user latitude and longitude points even when they are curled up on the couch with a laptop. Having a user's location means you can be smarter about the content you show or how you provide search results.

In this tutorial, I'll show how you can get user location data using JavaScript. We'll be using two common ways to access the coordinates, then I'll provide a way to merge them together for one geo-locator to rule them all.

Get out your compass. I'll show you the way.

Can you find your your way around geolocation code? Navigate to the edit link above and add your directions to this wiki article.

Contents

What you'll need

How Does Browser-Based Location Work?

You may be asking how this geo-location stuff works in a browser. After all, most laptops aren't outfitted with GPS units.

Both of the methods we'll use in this tutorial are based on Skyhook's database of WiFi hotspots. There are many thousands of known access points throughout the world, which means the result is surprisingly accurate in urban areas.

If you're writing the technology off, wait a tick, and let's gaze a bit into the future. A standard is being written for geolocation. The code shared in this tutorial is an interface to the location, not the location itself. Someday soon we'll have a much better method than WiFi hotspots for determining coordinates, but the code will likely be similar to what's in these examples.

So let's accept the shortcomings of browser geolocation for now and dive into the code.

Use Geode/Firefox 3.1

This example requires that your user has the Firefox browser and possibly the Geode plugin installed. The upside is that the syntax used here matches the geolocation API specification, so it will work as soon as other browsers add support.

Before we get to the code, make sure you have the software. You'll need either of these:

  • Firefox 3.0 with the plugin
  • Or 3.1 beta, which includes Geode as a core functionality

Enough preparation, let's grab the user's location using JavaScript. Copy this code into a new HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<title>Testing Geode/Firefox 3.1</title>
	<script type="text/javascript">
	function findLocation()
	{
	  navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
	}
	function foundLocation(position)
	{
	  var lat = position.latitude;
	  var long = position.longitude;
	  alert('Found location: ' + lat + ', ' + long);
	}
	function noLocation()
	{
	  alert('Could not find location');
	}
	</script>
</head>
<body>
	<button onclick="findLocation();">Click to find location</button>
</body>
</html>

Load it up and you should see a page with a single button, like this:

Click the button and you should see one of two results popped up in an alert box: some geo coordinates or a message that the location cannot be found.

Let's work backwards and first look at each of the functions that returned your results. The noLocation function gives the bad news if Geode couldn't find coordinates. It contains only the alert box call. The foundLocation function shows the coordinates if they could be found. It first saves the latitude and longitude to variables, then calls the alert.

The foundLocation function is passed the location inside the /position/ variable. So, where does that come from? The real workhorse of this example is the findLocation function and it's only one line long:

navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

The navigator.geolocation.getCurrentPosition function queries Geode for the user's location. That can take a few seconds, so rather than make the browser hang, it asks for two function references. First, the function to call when everything goes nicely. And second, the function to call if Geode failed. We already created those functions above, so we pass along foundLocation and noLocation, and hope for the best.

At this point, if your users are findable with Geode, you have their coordinates. What if they don't have access to Geode (either not using Firefox, or haven't installed the plugin)? Let's try using Gears instead.

Use Google Gears

This example requires that your user has Google Gears installed. The good news is that Gears works in multiple browsers. That's even worth the annoyance of a slightly different syntax than the previous example.

Before you go any further, make sure you do the following:

  1. Install Gears
  2. Save the gears_init file to the same directory as your test files

With that done, let's get at the user's location using JavaScript and Gears. Copy this code into a new HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<title>Testing Gears</title>
	<script type="text/javascript" src="gears_init.js"></script>
	<script type="text/javascript">
	function findLocation()
	{
	  var geo = google.gears.factory.create('beta.geolocation');
	  geo.getCurrentPosition(foundLocation, noLocation);
	}
	function foundLocation(position)
	{
	  var lat = position.latitude;
	  var long = position.longitude;
	  alert('Found location: ' + lat + ', ' + long);
	}
	function noLocation()
	{
	  alert('Could not find location');
	}
	</script>
</head>
<body>
	<button onclick="findLocation();">Click to find location</button>
</body>
</html>

Load it up and it looks the same as the previous example. You should see a page with a single button, like this:

Click the button and, like before, you should see one of two results popped up in an alert box: some geo coordinates or a message that the location cannot be found.

First, notice that we need to include the gears_init.js file. This contains functions that communicate with Gears on the user's machine. Before we use this code, let's look at the two functions that return the messages when the user clicks the button.

The noLocation function gives the bad news if Gears couldn't find coordinates. It contains only the alert box call. The foundLocation function shows the coordinates if they could be found. It first saves the latitude and longitude to variables, then calls the alert.

The foundLocation function is passed the location inside the /position/ variable. And /that/ comes from the findLocation function. All this power and it's only two lines long:

	  var geo = google.gears.factory.create('beta.geolocation');
	  geo.getCurrentPosition(foundLocation, noLocation);

First we initialize Gears, and create a new variable, /geo/, that we can use to access Gears functions. We waste no time and get straight at it. The geo.getCurrentPosition function queries Gears for the user's location. That can take a few seconds, so rather than make the browser hang, it asks for two function references. First, the function to call when everything goes nicely. And second, the function to call if Gears failed. We already created those functions above, so we pass along foundLocation and noLocation, and hope for the best.

At this point, if your users are findable with Gears, you have their coordinates. What if they don't have Gears installed? You could always try Geode above. Or, move on to the next section, where I'll show the function I wrote that lets you check /both/ at the same time.

Check 'em All With a Wrapper Function

The downside of accessing location within the browser is that, unless the user has Firefox 3.1 beta, an add-on is required to make it work. Since this is still a new technology and there are several different implementations, if you choose one you are missing out on user's that have another location add-on installed.

Until the geolocation specification becomes a true standard, we need something that will check Gears, Geode, and any others that come around. In this example, I'll share the function I wrote to look for Geode and, if it's not there, look for Gears.

Copy this code into a new HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<title>Testing Both Gears and Geode/Firefox 3.1</title>
	<script type="text/javascript" src="gears_init.js"></script>
	<script type="text/javascript">
	function findLocation()
	{
      var mygeo = findGeoProvider();
      mygeo.getCurrentPosition(foundLocation, noLocation);
	}

    function findGeoProvider()
    {
      if (navigator.geolocation)
        return navigator.geolocation;
      var geo = google.gears.factory.create('beta.geolocation');
      if (geo)
        return geo;
    }
	function foundLocation(position)
	{
	  var lat = position.latitude;
	  var long = position.longitude;
	  alert('Found location: ' + lat + ', ' + long);
	}
	function noLocation()
	{
	  alert('Could not find location');
	}
	</script>
</head>
<body>
	<button onclick="findLocation();">Click to find location</button>
</body>
</html>

Like in the previous two examples, the result is a single button on the page:

Try this out in multiple browsers and it will still work, whether the data comes from Geode or Gears.

Much of the code probably looks similar to the other examples. The foundLocation and noLocation functions are the same as before. The findLocation function is similar in that it calls to getCurrentPosition, but it first needs to determine whether to send that call to Geode or Gears.

The findGeoProvider function is where the voodoo goes down that determine the provider. Within the function there is a series of if statements. These check whether the object necessary to make the call for each geolocator exists. If it does, it returns that object, which stops any remaining if statements from being called.

I start with the Geode code, because it uses the syntax that may become a standard. If other browsers choose to support geolocation, they'll hopefully use this code instead of creating their own version.

Next I check for Gears. To do this, I have to attempt to initialize Gears and create a variable to access its functions. If that variable is able to be properly initialized, I return the object.

Even though this one function now checks two places, notice I still had to include the gears_init.js file. That's because the initialization process requires it.

My findGeoProvider function could be updated down the road if yet another browser location API is released. Hopefully everyone will migrate to the forthcoming standard, but you never can tell. One of the byproducts of innovation is that standards are passed over in order to make new features that aren't possible if the standards are supported.

Where To Go From Here

In this tutorial, I've shown you how to get at the user's location with both Geode and Gears. Now you're armed with the findGeoProvider function that will let you check both providers at once, writing the same code. What's left?

Everything. The possibilities of location-based applications are endless. Now that you have the latitude and longitude of your user, it's time to use it. Plot the location on a Google Map. You could also use Yahoo Maps. Or, why not make it work on any online map using Mapstraction?

You can use the coordinates to find nearby restaurants, or save the location to Fire Eagle. There are plenty of options, so you just need to decide where you're going and point yourself in that direction.

One thing we know: when you get there, your browser will be able to find you.

  • This page was last modified 00:26, 30 October 2008.
Edit this article
Reddit Digg
 
Subscribe now

Special Offer For Webmonkey Users

WIRED magazine:
The first word on how technology is changing our world.

Subscribe for just $10 a year