HTML5 geolocation

Geolocation api in HTML5 gives the current position of web user. It gives the latitude and longitude for geographic position.
API gives the navigator.geolocation object. This object packed with 3 methods
1)getCurrentPosition()
2)watchPosition()
3)clearWatch()
Example for current position of user
Note : navigator.geolocation.getCurrentPosition()
<html>
<head>
<script>
function getLocation() {
if (navigator.geolocation !== “undefined”) {
console.log(“browser supports the geolocation feature”);
navigator.geolocation.getCurrentPosition(function (pos) {
console.log(“Current position latitude is “, pos.coords.latitude);
document.getElementById(“latId”).innerHTML = pos.coords.latitude;
console.log(
“Current position longitude is “,
pos.coords.longitude
);
document.getElementById(“longId”).innerHTML = pos.coords.latitude;
});
} else {
console.log(“Browser does not support geolocation”);
}
}
</script>
</head>
<body>
Latitude : <span id=”latId”></span> <br />
Longitude : <span id=”longId”></span>
<hr/>
<button onclick=”getLocation()”>Get Location</button>
</body>
</html>
Example for watch location
Note : navigator.geolocation.watchPosition
<html>
<head>
<script>
function showPosition() {
var watchId;
if (navigator.geolocation !== “undefined”) {
console.log(“Browser supports the geolocation feature!”);
watchId = navigator.geolocation.watchPosition(function (pos) {
var lat = pos.coords.latitude;
var long = pos.coords.longitude;
if (lat !== preLat && long !== preLong) {
var latLong = lat + “,” + long;
var preLat = pos.coords.latitude;
var preLong = pos.coords.longitude;
console.log(
“The pos is “,
pos.coords.latitude,
pos.coords.longitude
);
}
});
} else {
console.log(“Browser does not supports the geolocation feature!”);
}
}
</script>
</head>
<body>
<divid=”map”></div>
<br/>
<button onclick=”showPosition()”>Show Location on map</button> |
<button onclick=”stopWatch()”>Stop watch</button>
</body>
</html>

Site Footer