Information Technology Reference
In-Depth Information
Delving into the Coordinates
OK, enough dancing around the edges! The
checkIn()
function performs the key tasks
in our little example.
function checkIn () {
var geoData = "";
if (supportsGeo()) {
navigator.geolocation.getCurrentPosition(function(position) {
geoData = position.coords.latitude + ", " + position.coords.longitude;
});
<!-- alert("Confirm geolocation access before clicking OK"); -->
} else {
geoData = "Your browser does not support HTML5 geolocation";
}
changeDiv ("myCheckIn",geoData);
}
The
geoData
variable eventually holds our resulting latitude and longitude. We invoke our
supportsGeo()
function to ensure our browser can support our intentions. Then we get
down to business by calling the
navigator.geolocation.getCurrentPosition()
function. This is one of the core HTML geolocation functions, and has pages and pages
For now, what you need to know is that
navigator.geolocation.getCurrentPosition()
is an asynchronous function, which in the form used here passes a call-back function to
be invoked once the browser and underlying hardware have responded to the request
for the caller's current location. Our
position
call-back assigns our
geoData
variable with
two data members: the
position.coords.latitude
and
position.coords.longitude
values, which equate to the caller's latitude and longitude.
All that remains is for us to call the utility
changeDiv()
function to update our HTML
page, and voila! Of course, we also ensure that browsers that don't support geolocation
are targeted with the appropriate message indicating no support for our geolocation
work.
NOTE:
You might observe that we have a commented-out call to an
alert()
, asking the user to
confirm geolocation access before continuing. If you haven't allowed web pages to freely ask for
your location (and there's no reason you should), then you'll need to confirm access when asked
by your browser. But even the fastest human will not be able to do this before the call to
navigator.geolocation.getCurrentPosition()
returns, even though it's asynchronous.
At this point, the call-back will return an error that our code currently doesn't catch (but see the
section "What Could Possibly Go Wrong" later in this chapter), and our example will silently fail.
Uncomment this alert in your testing to give yourself better control over the asynchronous
behavior of
navigator.geolocation.getCurrentPosition()
.