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 entries, 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 adding 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 geolocation API, however, and
geolocation services are not available at all times in all locations, 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.');}functionthrow_error(position){alert('Unable ...