HTML and CSS Reference
In-Depth Information
heading
(specified in degrees; north = 0, west = 90, etc.)
•
speed
(specified in meters/second,
NaN
if stationary)
•
These properties can be obtained by the callback function like this:
function successCallback(pos) {
var lat = pos.coords.latitude;
var long = pos.coords.longitude;
var accuracy = pos.coords.accuracy + " meters";
}
If the call was not successful, the
PositionError
object is passed to the error callback function. This object
includes a
code
and a
message
property. The error
code
will have one of three possible values:
•
1 -
PERMISSION_DENIED
•
2 -
POSITION_UNAVAILABLE
•
3 -
TIMEOUT
■
Your application will get the location and simply display it (and later map it). However, your script
could easily pass this information back to the server, which is a potential privacy issue. Since the browser cannot
control what the client does with this information, for privacy reasons the browser may block the access to the
geolocation
object. in this case the
PERMISSION_DENIED
error code is returned. i will demonstrate this later.
Caution
If the client is moving and you want to continuously monitor the current location, you could call the
getCurrentLocation()
function repeatedly using a
setInterval()
function. To simplify this, the
geolocation
object includes a
watchPosition()
function. This takes the same three parameters as the
getCurrentLocation()
function (success callback, error callback, and options). The callback function is then invoked whenever the
position changes. The
watchPosition()
function returns a timer handle. You can pass this handle to the
clearWatch()
function when you want to stop monitoring the position like this:
var handle = geolocation.watchPosition(callback);
...
geolocation.clearWatch(handle);
Displaying the Location
Now you'll add code to your application to get the current location and display it. The web page has a
span
element with an id of “lbl”. You'll get the
geolocation
object and call its
getCurrentLocation()
function. Both
the success and error callback functions will display the appropriate results in the
span
element.