Tuesday, December 19, 2017

Getting location using HTML5 in Browser

Getting location using HTML5 in Browser:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Finding Me</title>
<script>
function getLocation()
{
    // Check whether browser supports Geolocation API or not
    if (navigator.geolocation) { // Supported
        //navigator.geolocation.getCurrentPosition(getPosition);
        navigator.geolocation.getCurrentPosition(getPosition, catchError);
    } else { // Not supported
        alert("Oop! This browser does not support HTML5 Geolocation.");
    }
}
function getPosition(position)
{
    document.getElementById("location").innerHTML = 
        "Latitude: " + position.coords.latitude + "<br>" +
        "Longitude: " + position.coords.longitude + "<br>" +
        "Altitude: " + position.coords.altitude + "<br>" +
        "Timestamp: " + position.coords.timestamp;
}
function catchError(error) {
    switch(error.code)
    {
        case error.TIMEOUT:
            alert("The request to get user location has aborted as it has taken too long.");
            break;
    case error.POSITION_UNAVAILABLE:
            alert("Location information is not available.");
            break;
    case error.PERMISSION_DENIED:
            alert("Permission to share location information has been denied!");
            break;
    default:
            alert("An unknown error occurred.");
    }
}
</script>
</head>
<body>
    <h1>Finding Me</h1>
    <button onclick="getLocation()">Where am I?</button>
    <p id="location"></p>
</body>
</html>

Reference: https://www.codeproject.com/Articles/1184757/HTML-Geolocation

No comments:

Post a Comment