HTML 5 – Geo Location API
The HTML5 geolocation feature lets you find out the geographic coordinates (latitude and longitude numbers) of the current location of your website’s visitor. This feature is helpful for providing better browsing experience to the site visitor.
Check for Browser compatibility
The geolocation property of the global navigator object can be used to detect the browser support for the Geolocation API.
if (navigator.geolocation) {
// Get the user's current position
} else {
alert('Geolocation is not supported in your browser');
}
Get Current Location
The current location of the user can be obtained using the getCurrentPosition function of the navigator.geolocation object. This function accepts t, success callback function. If the location data is fetched successfully, the success callback function will be invoked with the obtained position object as its input parameter.
if (navigator.geolocation) {
// Get the user's current position
navigator.geolocation.getCurrentPosition(pos);
} else {
alert('Geolocation is not supported in your browser');
}
Success callback function
This callback function is invoked only when the user accepts to share the location information and the location data is successfully fetched by the browser. The location data will be available as a position object and the function will be called with the position object as its input parameter. A position object contains coords object will give you Latitude & Longitude.
function pos(position) {
document.write('Latitude: '+position.coords.latitude+'Longitude: '+position.coords.longitude);
}
Full Example
<html>
<head>
<title> Geo Location API </title>
<script type="text/javascript">
function getloc()
{
if(navigator.geolocation!="undefined")
{
navigator.geolocation.getCurrentPosition(display);
}
else
{
alert("Browser Do not Support GeoLocation API");
}
}
function display(pos)
{
alert("latitude :"+ pos.coords.latitude);
alert("longitude:"+ pos.coords.longitude);
}
</script>
</head>
<body>
<span id="sp"></span>
<input type="button" value="getlocation" onclick="getloc()" />
</body>
</html>