Basic GeoLocation in HTML5

No Gravatar

Every professional web developer knows that now is the time to start picking up HTML5. We all need to dip our toes in the water, pretend that it’s warm, and jump in. As you MAY have guessed by now, I tried HTML5 for the first time this week, and I’d like to share my experience. Bring some Doritos and a pair of flip-flops — the water’s amazing!

Before we Begin…

  • The map generation I’m writing about is all done with Google’s map API.
  • The examples provided here are extremely basic, and are meant to be that way. We can save the more complex examples for another day.
  • Credit goes to maxheapsize.com and html5demos.com for their pioneering HTML5 samples.
  • Various code is scattered all over this post. The sample source code will be displayed in its entirety at the end of the post.

Initial Approach

After spending some time wrapping my head around HTML5, I decided that I would just write a test page with some arbitrary code, rather than trying to completely understand HTML5 through the documentation. For me, it was the best way to learn, and I would recommend everyone else to do so as well.

I decided to create a page that used GeoLocation to pinpoint the user’s initial location, mark their location on a map, and allow them to enter search keywords for jobs. The page would then return a list of results for the keywords they had entered, and mark these jobs on the map. The user could also enter a different zip code, state, or city/state in a location field, and the page would retrieve new job results, redraw the map, and place markers on the new jobs in the list.

GeoLocation Detection

Although I would like to demonstrate my GeoLocation search in more depth, I would like just cover simple GeoLocation detection and how it can be used.

To get the intial location, all we need to do is call the browser’s navigator object. Remember that not all browsers support all available HTML5 features.

<script type="text/javascript">
function initGeolocation()
{
     if( navigator.geolocation )
     {
          // Call getCurrentPosition with success and failure callbacks
          navigator.geolocation.getCurrentPosition( success, fail );
     }
     else
     {
          alert("Sorry, your browser does not support geolocation services.");
     }
}

function success(position)
{
      // GeoPosition Object
     alert("Your coordinates are " + position.latitude + ", " + position.longitude);
}
function fail()
{
     // Could not obtain location
}

// Make sure to add onload="initGeolocation();"
// to your  tag!
<body onload="initGeolocation();">
.....
</body>

Not bad. One function call, and you have the user’s coordinates. Let’s make good use of these coordinates — this is where Google maps comes into play. Let’s draw a basic map, and place a marker on the user’s coordinates.



First, we need to include the Google Maps JS API. Make sure you include the “sensor=false” argument — this tells Google to not detect the user’s location.

<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

Now, we’ll create a placeholder for the map.

<!-- Prepare a div for the canvas -->
<!-- The div width and height will determine the size of the map -->
<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; margin: 20px;"></div>

Finally, we’ll modify the “success” function created in the last block of code.

<script type="text/javascript">
var map; // Define a global to hold the map object
function success(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!"
            });
}

It looks daunting, but the Maps API is really doing all of the work. We’re really just passing around configuration options.

What have we learned?

HTML5 Geolocation is incredibly simple, and the Google Maps API makes GeoLocation a powerful function.

Other things you should know

  • The doctype definition has changed for HTML5. You simply need to use “<!DOCTYPE HTML>” prior to your <html> tag. You can see this in the source code below.
  • Many Google Maps API code samples will use “GMap” instead of “google.maps” — such code was written for the older versions of the Google Maps API. Consult the Maps API Reference before using the function.
  • The Google Maps API only allows one thousand calls per day, per user. Be careful not to get banned from the service while you are in development. (Thankfully, however, the call is tracked per user, not per website).
  • There is a Javascript file called HTML5 Shim that will add support for various HTML5 functionality on incompatible browsers. For simplicity’s sake, we have not covered it here. If you are creating HTML5 functionality for a live site, and not just for testing purposes, you will want to research and implement the HTML5 Shim.

And, since you have all been waiting so patiently, here is the entire sample source code. Copy, paste, and impress your boss.

<!DOCTYPE HTML>
<html>
<head>
<title>Basic GeoLocation Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
    function initGeolocation()
    {
            if( navigator.geolocation )
            {

              // Call getCurrentPosition with success and failure callbacks
              navigator.geolocation.getCurrentPosition( success, fail );
        }
        else
        {
              alert("Sorry, your browser does not support geolocation services.");
        }
    }

     var map;
     function success(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 fail()
        {
              // Could not obtain location
        }
        </script>
</head>
<body onload="initGeolocation();">
<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>

Again, thanks to maxheapsize.com and html5demos.com, whose HTML5 samples gave me a running start. I hope you find HTML5 to be an exciting new way to develop web applications!

3 Responses to “Basic GeoLocation in HTML5”

Leave a Reply