Show Me the Code
The geolocation API centers around a new property
on the global navigator
object:
navigator.geolocation
.
The simplest use of the geolocation API looks like this:
function get_location() {
navigator.geolocation.getCurrentPosition(show_map);
}
Thereâs no detection, no error handling, and no options. Your web application should probably include at least the first two of those. To detect support for the geolocation API (see Geolocation), you can use Modernizr:
function get_location() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(show_map);
} else {
// no native support; maybe try Gears?
}
}
What you do without geolocation support is up to you. Iâll explain
the Gears fallback option in a minute, but first I want to talk about what
happens during that call to getCurrentPosition()
. As I mentioned at the start of this chapter, geolocation
support is opt-in. That means your browser will never
force you to reveal your current physical location to a remote server. The
user experience differs from browser to browser. In Mozilla Firefox,
calling the getCurrentPosition()
function of the geolocation API will cause the browser to
pop up an âinfobarâ at the top of the browser window. The infobar looks
like Figure 6-1.
Figure 6-1. Geolocation infobar
Thereâs a lot going on here. As the end user, you:
Are told that a website wants to know your location ...
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.