HTML and CSS Reference
In-Depth Information
Both the success and error callback methods receive one parameter from the Geolocation
API. The success method receives a position object, whereas the error method receives
an error object. The position object exposes two properties: coords and timestamp . The
timestamp property indicates the time at which the coords were received. The coords property
is itself a coordinates object that contains the latitude, longitude, altitude, heading, and speed
of the device's current position and/or relative to the last position acquired. The positionError
object contains two properties: one for the code and one for the message. You can use these
objects in Listing 1-5 by adding the following fragments:
<script>
function successPosition(pos) {
var sp = document.createElement("p");
sp.innerText = "Latitude: " + pos.coords.latitude +
" Longitude: " + pos.coords.longitude;
document.getElementById("geoResults").appendChild(sp);
}
function errorPosition(err) {
var sp = document.createElement("p");
sp.innerText = "error: " + err.message; + " code: " + err.code;
document.getElementById("geoResults").appendChild(sp);
}
</script>
Figure 1-54 shows the output from running this code successfully.
FIGURE 1-54 Displaying current location as retrieved by the Geolocation API
Using the watchPosition method
The second method available on the geolocation object is the watchPosition method, which
provides a built-in mechanism that continuously polls for the current position. Here's an
example of using the method:
geoLocator.watchPosition(successCallBack,errorCallback,positionOptions)
The watchPosition method takes the same set of parameters as the getCurrentPosition
method but returns a watchPosition object:
var watcher = geoLocator.watchPosition...
After running this code, the watcher variable holds a reference to the watchPosition
instance being invoked, which can be useful later. The method calls the success callback
method every time the Geolocation API detects a new location. The polling continues forever
unless it you stop it. This is where the watcher object comes in handy; you can cancel polling by
 
Search WWH ::




Custom Search