The Geolocation API allows JavaScript programs to ask the browser for the user’s real-world location. Location-aware applications can display maps, directions, and other information relevant to the user’s current position. There are, of course, significant privacy concerns here, and browsers that support the Geolocation API always ask the user before allowing a JavaScript program to access the user’s physical location.

Browsers that support the Geolocation API define navigator.geolocation. This property refers to an object with three methods:


Request the user’s current position.


Request the current position, but also continue to monitor position and invoke the specified callback when the user’s position changes.


Stop watching the user’s location. The argument to this method should be the number returned by the corresponding call to watchPosition().

In devices that include GPS hardware, very precise location information can be obtained from the GPS unit. More commonly, however, location information comes via the Web. If a browser submits your Internet IP address to a web service, it can usually determine (based on ISP records) what city you are in (and it is common for advertisers to do this on the server side). A browser can often obtain an even more precise location by asking the operating system for the list of nearby wireless networks and their signal strengths. ...

Get JavaScript: The Definitive Guide, 6th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.