HTML and CSS Reference
In-Depth Information
CHAPTER 2
Geolocation for Publishers
Location-based web sites have become so commonplace that we frequently take their
functionality for granted. Type Starbucks into your Google search bar, and you'll get a
list of numerous store locations within your immediate vicinity, without you even
needing to specify a town or city. Flickr's map page has a “Find my location” button
that will show you pictures taken in areas near you. And if you want to geotag your
blog entris, WordPress has a plugin for that.
With the advent of HTML5, building geolocation functionality into web content has
become incredibly easy, thanks to the release of the Geolocation API , which provides
a standardized mechanism across all major web browsers for querying and receiving
user location data.
Obtaining location data via the web browser requires just one line of JavaScript code
to your script:
navigator.geolocation.getCurrentPosition( callback_function );
Where callback_function is the function that will be called by the browser when it
completes its attempt to retrieve location data. Not every browser supports the geolo-
cation API, however, and geolocation services are not available at all times in all loca-
tions, so you'll probably want to build in a bit more error handling—for example:
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition( callback_function , throw_error);
} else {
alert('Your browser/ereader does not support geolocation. Sorry.');
}
function throw_error(position) {
alert('Unable to geolocate you. Sorry.');
}
The Geolocation API returns to two properties that contain location data to your call-
back function: position.coords.latitude , which contains the user's latitude, and posi
tion.coords.longitude , which contains his longitude. That's neat, but unless your
 
Search WWH ::




Custom Search