HTML5 Tutorial: Geolocation

In this tutorial, we will learn about an aspect of HTML5 that you may already use on a daily basis: Geolocation: In short, geolocation allows the browser to identify your location and tailor content specific to wherever you are at that moment. If you own a smartphone, you’ve probably already come in contact with geolocation enabled browsers.

If you haven’t experienced geolocation-enabled browsers yet, let me explain why they are useful. Let’s say you’re on the road and get hungry for some tacos. Using Google via your smartphone browser, just type in “tacos”, and it identifies a list of nearby restaurants that sell tacos. Better yet, it works for nearly anything you’re looking for, like shopping malls, gas stations, grocery stores, etc…

Here’s a good business case for working geolocation into your apps. You can make a mobile app for your salespeople that will pull up directions to customer locations based on their current location. That might be pretty handy for business travelers.

Geolocation is determined using a few different methods, such as IP addresses, wifi access points, cell tower triangulation (calculates position based on distance from cell towers), and GPS receivers. As a result, geolocation on a desktop browser is far less accurate than on a mobile browser. For instance, the most basic method for determining location on a cell phone is cellular tower triangulation, which is accurate within a few hundred meters. On the flip side, the most basic method for determining a desktop browser’s location is the IP address, which can vary by many, many miles. For example, on the few geolocation demos I ran on my PC, each placed me about 20 miles away from my actual location.

One more thing: For those worried about privacy, don’t worry. Geolocation support is completely opt-in. That means the browser can never automatically find your location. It must get your approval first.

Now that you understand what geolocation is and what it is good for, let’s learn how to use it.

How does it work?

Adding geolocation to your web pages requires some knowledge of javascript. If you’re not too familiar with javascript, don’t worry…it won’t be that difficult. In fact, I will walk you through the steps required to add basic geolocation capabilities to your web apps.
First, you must understand how to detect whether or not the user’s browser currently offers geolocation support. I will show you the code necessary to perform this task and then explain how it works. Here’s the code to determine whether or not the user’s browser supports geolocation:
Code:

function TestGeo()    {
         if (navigator.geolocation)     {
              navigator.geolocation.getCurrentPosition( TestMap, error );      }
        else     {
              alert("Sorry, but it looks like your browser does not support geolocation.");
        }
    }

Let’s go through that code so you know exactly what’s going on. The first line names the function that we will call later on in the page. I’ve named it “TestGeo”, but you can name it whatever you like. The next line checks to see if your browser supports geolocation. If the answer is “yes”, the browser moves onto the next line, which runs the callback function which I’ve called “TestMap” (more on this later). Additionally, if the answer is “yes”, but the user denies location access (or some other error occurs), the application will run the second callback function, which I’ve called “error”. Lastly, if the browser does not support geolocation, it follows the command listed under “else”, and displays an alert box. Using this code, your page will check for browser geolocation support and display an error message if the browser offers no support.

Okay, so what happens if the browser does support geolocation, and the user agrees to share their location? If all that happens, the page runs the first callback function (“TestMap”). This is where we actually determine the user’s location. Now, this function can have two different properties: Coords and timestamp. The timestamp provides the time that the location was discovered. The “coords” property has a few different options, all of which are pretty easy to understand:

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

Keep in mind that not all of those options are available on every device. Only latitude, longitude, and accuracy will be available on every browser. Obviously, not every device can share altitude, heading, and speed with the browser. Let’s take a look at how our TestMap function determines the user’s location:
Code:

function TestMap(position) {
	var latitude = position.coords.latitude;
	var longitude = position.coords.longitude;  
	alert("Your coordinates are " + position.coords.latitude + ", " + position.coords.longitude);
	}

Let’s run through this function so you understand what’s happening. The first line names the function, which if you remember, is the first callback function in the last example. The next two lines finds the user’s longitude and latitude. Finally, the last line displays the user’s longitude and latitude in an alert box. Now, this function only runs if two things happen: The browser must support geolocation and the user must agree to share their location. What happens if the browser supports geolocation, but the user doesn’t share their location? If that’s the case, we move on to this function:
Code:

function error() {
		alert("Cannot locate user");
		}

You might remember the “error” function from earlier on in the page. It was the second option contained in the “getCurrentPosition” function. Basically, if the user agrees to share location, the “getCurrentPosition” function uses the first option (TestMap). If not, it goes to the second (error).

In a moment, I will show you how all of this fits in a web page. But first, you need to learn about a few more options for the getCurrentPosition function. I’ve already told you about the first two options, but there are a few more. These options can be added to the getCurrentPosition function.

  • Timeout: Sets the maximum time the application should wait for the position.
  • enableHighAccuracy: If the device offers support, it will provide the most accurate position possible. For example, you can enable high accuracy on a smartphone when you turn the gps on. This wouldn’t work on a desktop browser.
  • maximumAge: Checks when the last location was found and determines if the browser should find the location again. For instance, if you set the maximum age to 10000 (milliseconds), the browser will only reuse the location if it was found less than 10 seconds ago.

Now, let’s see how we add these options to the getCurrentPosition function. I will use the previous example, but will add a third option, as seen below:
Code:

function TestGeo()
    {
         if (navigator.geolocation) 
            {
              navigator.geolocation.getCurrentPosition( TestMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
        }
        else
        {
              alert("Sorry, but it looks like your browser does not support geolocation.");
        }
    }

Basically, I’ve added 3 new options to the getCurrentPosition function. The first tells the browser to only use the current location if it was found less than 30 seconds ago. The second tells the browser to stop looking for the location if not found in 10 seconds. The third tells the browser to provide the most accurate location possible.

Okay, now let’s put everything together and look at a very basic geolocation-aware web page. In this example, we will determine whether or not the browser supports geolocation, ask the user to share their location, and present an alert box with their longitude and latitude. Of course, the alert box will only appear if the user agrees to share their position. First, here’s the code:
Code:

<!DOCTYPE HTML>
<html>
<head>
<title>The most basic form of geolocation</title>
<script type="text/javascript">

function TestGeo()
    {
         if (navigator.geolocation) 
            {
              navigator.geolocation.getCurrentPosition( TestMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
        }
        else
        {
              alert("Sorry, but it looks like your browser does not support geolocation.");
        }
    }

function TestMap(position) {
	var latitude = position.coords.latitude;
	var longitude = position.coords.longitude;  
	alert("Your coordinates are " + position.coords.latitude + ", " + position.coords.longitude);
	}
	
function error() {
		alert("Cannot locate user");
		}
</script>

</head>
<body onload="TestGeo();">

</body>
</html>

Now, let’s test that code out in a browser. The browser should ask you for your permission to share your location. If you allow it, an alert box will pop up and display your latitude and longitude position. If you are using Internet Explorer, the alert box will tell you that your browser does not support geolocation. Here’s the live example:

http://www.mrc-productivity.com/forum/geo2.html

Now, obviously showing your users their latitude and longitude isn’t very helpful unless there’s a map. So, let’s add a map. I’m going to take the same code I just used and add a Google Map to it. This gets a bit more complicated than the last example, and we’ll need a fair amount of extra code to make this work. However, all the code is documented, so you should be able to understand what’s going on. First, we’ll look at the code, and then we’ll look at an example. Here’s the code:
Code:

<!DOCTYPE HTML>
<html>
<head>
<title>Geolocation With a Map</title>
//Add the the Google Maps API
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function TestGeo()
    {
         if (navigator.geolocation) 
            {
              navigator.geolocation.getCurrentPosition( TestMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
        }
        else
        {
              alert("Sorry, but it looks like your browser does not support geolocation.");
        }
    }
//Create a new map variable	
var map;
     function TestMap(position)
     {
           // Define the coordinates as a Google Maps LatLng Object
           var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

           // Prepare the map options
           var mapOptions =
          {
                      zoom: 10,
                      center: coords,
                      mapTypeControl: false,
                      navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
                      mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            // Create the map, and place it in the map_canvas div
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            // Place the initial marker
            var marker = new google.maps.Marker({
                      position: coords,
                      map: map,
                      title: "Your current location!"
            });
        }
	
function error() {
		alert("Cannot locate user");
		}	

</script>

</head>
<body onload="TestGeo();">
<div id="map_canvas" style="width: 600px; height: 400px; border-right: 1px solid #666666; border-bottom: 1px solid #666666; border-top: 1px solid #AAAAAA; border-left: 1px solid #AAAAAA;"></div>
</body>
</html>

Now that you’ve seen the code, let’s take a look at the example. This page will ask for your permission to access your location and, if allowed, it will pull up a map with your location. Granted, if using a desktop browser, the position isn’t very accurate (at least for me).

http://www.mrc-productivity.com/forum/geoMap.html

So, there you have it! Now you know how to add a map with geolocation to a web app. Obviously, there are many different things you can do with geolocation, but hopefully this provides a solid foundation for you if you feel like toying with geolocation any further.

Conclusion

Geolocation has really gained in popularity over the last couple years. Many web services add location into their apps, like Twitter, Facebook, Foursquare, etc… Anyone can create geolocation-aware web pages/applications with minimal javascript knowledge. There are plenty of different ways to use these capabilities, many of which are very beneficial for business applications. Now that you understand the basics, maybe you can create some geolocation apps for your business!

Related Posts:

10 thoughts on “HTML5 Tutorial: Geolocation

  1. Have tried this code aswell as several other tutorials.
    The geoMap.html works great in my browser, although when copying exact code and opening .html file, i receive a javascript alert “cannot locate user”

    any suggestions on what i am doing wrong?

  2. This is perfect, I have been searching for ages to find a bit of code to add to my website.

    How do you go about extending it further so not only would someone visiting your site see their current location but they see for example customer locations nearby?

    Kindest Regards

    Warren

  3. Great blog. I too would like to know how to incorporate this code with an existing google map that has other waypoints already plotted. Is this possible?

Leave a Reply

Your email address will not be published. Required fields are marked *