geo.js to the Rescue
geo.js is an open source, MIT-licensed JavaScript library that smooths
over the differences between the W3C geolocation
API, the Gears API, and the various
APIs provided by mobile platforms. To use it, youâll need
to add two <script>
elements at
the bottom of your page. (Technically, you could put them anywhere, but
putting scripts in your <head>
will make your page load more slowly. So donât do that!)
The first script is gears_init.js, which initializes Gears if itâs installed. The second script is geo.js. You can include them in your page using code like this:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dive Into HTML 5</title> </head> <body> ... <script src="gears_init.js"></script> <script src="geo.js"></script> </body> </html>
Now youâre ready to use whichever geolocation API is installed:
if (geo_position_js.init()) { geo_position_js.getCurrentPosition(geo_success, geo_error); }
Letâs take that one step at a time. First, you need to explicitly
call an init()
function. The init()
function returns true
if a supported geolocation
API is available:
if (geo_position_js.init()) {
Calling the init()
function does
not actually find the userâs location; it just verifies that finding the
location is possible. To actually find the userâs location, you need to
call the getCurrentPosition()
function:
geo_position_js.getCurrentPosition(geo_success, geo_error);
The getCurrentPosition()
function will trigger the browser to ask for permission to ...
Get HTML5: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.