Using HTML5 Geolocation API Navigator Object
The Navigator object is not new in HTML5 and if you look at reference document for JavaScript, you will be able to find information about it. However, HTML5 takes navigator object to the next level. Let’s explore how to use Navigator object in HTML5 Geolocation API.
First thing first, we need to make sure that end user browser can support Geolocation API. Below is the HTML5 boilerplate for this kind of checking.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
if(navigator.geolocation) {
alert('Supports');
} else {
alert('Does not support');
}
</script>
</body>
</html>
Next, we need to examine three methods available as part of the navigator.geolocation object.
- getCurrentPosition() – get current position of the user. This method can be called asynchronously
- clearWatch() – sets monitoring of a user to stop
- watchPosition() – sets monitoring of a user to start
We are ready to start coding our application for displaying current position of a user now. Below is a code snippet that uses navigator object to get current position of a user and checks for user’s browser compatibility. Once you gain access to a user coordinates, its up to you how to use it.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(){}, function(){});
} else {
alert('Does not support');
}
</script>
</body>
</html>
The getCurrentPosition has three different arguments that you can pass to it while calling it within your code.
- enableHighAccuracy - bool type of argument which allows you use GPS if available
- maximumAge - millisecond type of argument that set age limit of how recent current location detection needs to be
- timeout - millisecond type of argument that set when timeout needs to occur
Complete example of how to use HTML5 Geolocation API Navigator Object
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function okGeo(position) {
alert('Your position: '+position);
}
function failGeo(error) {
alert('There was a problem: '+error);
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo, failGeo);
} else {
alert('No support for Geo');
}
</script>
</body>
</html>