In addition to adding new and powerful tags, HTML5 also includes an extended JavaScript API. This new API allows developers to implement advanced features without additional plug-ins or requiring software downloads.
Included in HTML5's JavaScript APIs (or as a separate draft, depending on who you ask) is the ability to capture, with permission, the user's approximate coordinates in longitude and latitude. While this interface is not perfect (it may point to a user's Internet service provider on occasion), it can provide very useful information. For example, if a shopper visits a multi-channel merchant's website and looks for physical store locations, the site could check the user's geolocation and organize the list of locations by distance from the shopper's current position. The site could also plot the shopper's position on a map relative to the position of a store.
In mobile applications, geolocation in conjunction with Google Maps or Yahoo! Maps could provide a shopper with turn-by-turn directions to a retailer's store.
At the time of writing, recent versions of Mozilla Firefox, Google Chrome, and Apple Safari provided some support for geolocation, but only Firefox really applies it well, thus far.
Calling the Basic Geolocation API
At its most basic, calling the geolocation API is simple: (1) check to learn if the browser supports geolocation; (2) if the answer is yes, use getCurrentPosition() along with a function that accepts the position; (3) do something with that position.
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
doSomething();
});
}
For a more practical example, this function, which was tested in Firefox, will display a set of coordinates.
function outPut()
{
var tDiv = document.getElementById('wrapper');
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
tDiv.innerHTML = lat + ' ' + lng;
});
}
else
{
var stuff = 'this is stuff';
tDiv.innerHTML = stuff;
}
}
outPut();
Applying the Location Data
With the location data in hand, it is easy to pass that data to a map API. Here is an example using Google Maps version 3, which I selected because it does not require an app key or registration.
In the HTML, I included a div with the id of "map." Ultimately, this is where I will tell the Google Maps API to place the AJAX map. I also reference the API at the bottom of the page, just before my own external JavaScript file is called. I am setting "sensor" to "false" to let the Google Maps API know that I will not be using a device's internal GPS, which is mainly for mobile devices.
I have also included a "loading" span, because geolocation can take some time, and I want a way to indicate to the user that the page has not stopped working. There is also a link provided to start the geolocation and map-making process.
<!doctype html> <html lang="en"> <head> <title>Getting Started with Geolocation</title> <link type="text/css" rel="stylesheet" href="style.css"> <link rel="icon" type="image/png" href="favicon.png"> </head> <body> <div id="wrapper"> <h2>HTML5 Geolocation Example</h2> <div id="btn"> <a href="#">Geolocate</a> <span id="loading"></span> </div> <div id="map"> </div> </div><!--end wrapper--> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script src="js.js"></script> </body> </html>
Next, I wrote a short style sheet to make the example a little easier to look at. Also, it is important to set a width and height for the map, which I did in the last line of the style sheet.
#wrapper {margin: 50px auto; width:570px;}
#btn {margin: 10px 0; }
#btn a {color: #000; text-decoration: none; padding: 10px; background: #888; border: #000 solid 1px; }
#loading {padding: 10px 0 10px 25px;}
#map {width: 560px; height: 270px; margin-top: 25px; border: #000 solid 5px;}
The JavaScript managing the geolocation and map placement has a few tasks to complete, starting with a simple event listener.
document.onclick = outPut;
The function adds some variables required for the Google Maps API.
function outPut(e)
{
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
The function outPut, next identifies the source of the click, and then takes action if it is my "geolocate" link. Note that I have not done anything in this example to support Microsoft's Internet Explorer (IE). Current versions of IE do not support geolocation, so I saved a little time by skipping this step.
This section of the code also creates a variable to represent the "map" div, and adds "loading" to the page, once a user clicks.
if(e.target.parentNode.id == 'btn')
{
var tDiv = document.getElementById('map');
var loD = document.getElementById('loading');
loD.innerHTML = 'Loading';
Next, the JavaScript checks to ensure the browser has geolocation capabilities, and, if so, passes the longitude and latitude data to the Google Maps API.
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var showLo = new google.maps.LatLng(lat,lng);
map.setCenter(showLo);
var marker = new google.maps.Marker({position: showLo, map: map, title: 'You are here'});
loD.innerHTML = 'Success.';
});
}
Finally, I added a bit of code to manage browsers that do not support geolocation.
else
{
var err = 'For some reason geolocation is not working';
tDiv.innerHTML = err;
}
}
}
I have put all of the JavaScript together so that you can see it in context.
document.onclick = outPut;
function outPut(e)
{
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
if(e.target.parentNode.id == 'btn')
{
var tDiv = document.getElementById('map');
var loD = document.getElementById('loading');
loD.innerHTML = 'Loading';
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var showLo = new google.maps.LatLng(lat,lng);
map.setCenter(showLo);
var marker = new google.maps.Marker({position: showLo, map: map, title: 'You are here'});
loD.innerHTML = 'Success.';
});
}
else
{
var err = 'For some reasons geolocation is not working';
tDiv.innerHTML = err;
}
}
}
Summing Up
HTML5 geolocation is still in the early phases of browser acceptance, but it has a lot to offer and is well worth becoming familiar with. May I suggest trying this code or similar in Firefox. Please let me know how it works in the comments below.
Resources
- HTML5 Rocks Presentation
- World Wide Web Consortium's Geolocation API Specification
- Remy Sharp's HTML5 Geolocation Demonstration
This article is filed under HTML, XHTML, XML & CSS and has the following keyword tags: HTML5, geolocation.
