HTML and CSS Reference
In-Depth Information
Getting a One-Time Position
Getting the position of the user is simple enough; just call navigat-
or.geolocation.getCurrentPosition with a callback. This triggers a notification at the top of the
browser, as shown in Figure 23-1 , giving the user the power to allow or deny the request. If you supply a second
callback, that callback is called if the browser couldn't get the location due to a denied request or other error.
Figure 23-1: The geolocation permission dialog.
To see the data in the console that's returned from a request, you can enter the code in Listing 23-1 into a file
called position.html , load the page in a desktop browser, and open up the JavaScript console.
Listing 23-1: Getting a one-time position
<html lang="en">
<meta charset="UTF-8">
<title>Grabbing the position</title>
function logPosition(position) {
function positionError(error) {
Examining the console shows you the result of the request. If you denied the request or the system couldn't
look up your location, the positionError method is called with a PositionError object. If you run this
from a file:// URL, Chrome will give you an error by default so you'll want to run it from localhost .
If the geolocation was successful, the logPosition callback is called with a Position object, which is
logged to the console, as shown in Figure 23-2 .
Search WWH ::

Custom Search