Using HTML5 Geolocation API Position Object
The HTML5 Position object is returned when you successfully gained access to geolocation of the device running HTML5 application. This object was created after you make a call to getCurrentPosition and browser detects user’s location.
The HTML5 Position object has several properties that are essential for getting information about user’s location.
- timestamp - Position object property which returns date and time when location was detected by the user browser
- coords.latitude - Position object property which returns the latitude of the location. Return type is in degrees
- cooords.longitude - Position object property which returns longitude of the browser location. Returns data in degrees
- coords.accuracy - Position object property which returns in meters accuracy of the browser position
- coords.altitude - Position object property returns altitude of the browser
- coords.altitudeAccuracy - Position object property which returns accuracy of the altitude reading of the browser
- coords.speed - Position object property which returns speeds in comparison to prior position of the browser
- coords.heading - Position object property which returns an angle in degrees
The HTML5 Geolocation API guarantees coords.latitude, coords.longitude, and coords.accuracy to be implemented across platforms and browsers. All other properties are support differently by major browser vendors.
Let’s look at the code that requires in order to gain access to Position object properties and values.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function okGeo(position) {
alert('latitude: '+position.coords.latitude);
alert('longitude: '+position.coords.longitude);
alert('accuracy: '+position.coords.accuracy);
}
function failGeo(error) {
alert('Houston, we have a problem: '+error);
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(okGeo, failGeo);
} else {
alert(‘Browser does not support Geolocation API');
}
</script>
</body>
</html>
We can use this snippet of code and apply to google maps for instance. In order to that we need to modify above mentioned snippet of geolocation API code by inserting a link to google maps.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function okGeo(position) {
document.location = 'http://maps.google.com/maps?q='+position.coords.latitude+','
+position.coords.longitude;
}
function failGeo(error) {
alert('Houston, we have a problem: '+error);
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(okGeo, failGeo);
} else {
alert(‘Browser does not support Geolocation API');
}
</script>
</body>
</html>