HTML and CSS Reference
In-Depth Information
} else if (err.code == 2) {
error('Your location information is unavailable.')
} else if (err.code == 3) {
error('The request to get your location timed out.')
} else {
error('An unknown error occurred while requesting your location.')
}
}
// output lat and long
function printLatLong(lat, long) {
$('body').append('<p>Lat: ' + lat + '</p>');
$('body').append('<p>Long: ' + long + '</p>');
}
function error(msg) {
alert(msg);
}
</script>
Discussion
The
navigator
object gives us access to the new
geolocation
object. The
geolocation
object has the following methods:
•
getCurrentPosition()
returns the user's current position.
•
watchPosition()
returns the user's current position, but also continues to monitor
the position and invoke the appropriate callback every time the position changes.
•
clearWatch()
ends the
watchPosition()
method's monitoring of the current
position.
When determining the location of the Internet device, first check that the user's browser
supports the Geolocation feature natively. If it does, call the
getCurrentPosition()
method:
if (navigator && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geo_success, geo_error);
} else {
error('Geolocation is not supported.');
}
Since this method executes asynchronously, pass it two callback functions:
geo_suc
cess
and
geo_error
. The error callback is passed a
position error
object that contains
a
code
and a
message
property. The
code
can be one of the following:
0
Unknown
1
Permission Denied
2
Position Unavailable
3
Timeout