HTML and CSS Reference
In-Depth Information
Using the Geolocation API
Location services have become a large part of most people's lives. From routing and
navigation to just finding nearby points of interest or checking into their favorite social
community sites, more and more people are using some form of location services. Loca-
tion services depend on the Global Positioning System (GPS), IP addresses, and other device
characteristics. You can take advantage of geolocation in web applications by leveraging
browsers that support the Geolocation API.
You can get a reference to the Geolocation API from the window.navigator property, as
follows:
var geoLocator = window.navigator.geolocation;
This code saves a reference to the Geolocation API in a variable to provide shorthand
access to the API during future use. A good practice is to ensure that the client's browser
supports the Geolocation API by making sure that the reference is actually present.
The Geolocation API supports three key methods that you use to interact with it:
getCurrentPosition , watchPosition , and clearWatch .
Using the getCurrentPosition method
Here's an example of using the getCurrentPosition method:
getCurrentPosition(positionCallback, [positionErrorCallback], [positionOptions])
You use getCurrentPosition to get exactly what its name indicates—the current position
of the user or the device in which the application is running. This method takes one required
parameter and two optional parameters. The first parameter is a callback method that the API
calls after the current position is determined. The second parameter is optional, but it's also a
callback function called when an error occurs. The callback method you specify here should
handle any errors that can occur when trying to get the current position. The last optional
parameter is a special object called PositionOptions , which lets you set some special options
that control how the getCurrentPosition method behaves. Table 1-17 lists the possible values.
TABLE 1-17 Properties available on the PositionOptions object
Property
Description
This causes the method to be more resource intensive if set to true. The
default is false. If true, the getCurrentPosition method tries to get as close
as it can to the actual location.
enableHighAccuracy
This specifies a timeout period for how long the getCurrentPosition method
can take to complete. This number is measured in milliseconds and defaults
to zero. A value of zero represents infinite.
timeout
 
 
Search WWH ::




Custom Search