Geolocation

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:

navigator.geolocation.getCurrentPosition()

Request the user’s current position.

navigator.geolocation.watchPosition()

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

navigator.geolocation.clearWatch()

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 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.