Home Blog CV Projects Patterns Notes Book Colophon Search

Browser Geolocation

24 Jan, 2017

Simple demo:

<html>
<head>
</head>
<body>
  <div id="map"></div>
  <div id="msg"></div>
  <script>
var msg = document.getElementById("msg");
function getLocation() {
    if (navigator.geolocation) {
        msg.innerHTML = "Requesting geolocation (it can take a few seconds after you allow the request for the position to actually be obtained)...";
        // https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions
        navigator.geolocation.getCurrentPosition(showPosition, showError, {timeout: 2000});
    } else {
        msg.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    console.log(position);
    window.p = position;
    msg.innerHTML = "Success, position is: " + position.coords.latitude + ", " + position.coords.longitude;
    var latlon = position.coords.latitude + "," + position.coords.longitude;
    var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false";
    document.getElementById("map").innerHTML = "<img src='"+img_url+"'>";
}


function showError(error) {
    msg.innerHTML = "Error:" + JSON.stringify(error);
    switch(error.code) {
        case error.PERMISSION_DENIED:
            msg.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            msg.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            msg.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            msg.innerHTML = "An unknown error occurred."
            break;
    }
}

console.log("Ready");
getLocation();
console.log("Requested location");
</script>
</body>
</html>

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.