<div>Latitude: <span id="lat"></span></div>
<div>Longitude: <span id="lon"></span></div>
<div>
<button id="currPos">Get Current Position</button>
</div>
<div id="error"></div>
body {
margin: 0;
padding: 15px;
color: #222;
font: normal normal normal 1rem/1.6 Nunito Sans, Helvetica, Arial, sans-serif;
}
div {margin-bottom: 10px;}
button {
background-color: #3da4ab;
border: none;
color: #fff;
padding: 10px;
font-size: 1.05rem;
border-radius: 2px;
cursor: pointer;
}
button:hover {
background-color: #0e9aa7;
}
document.addEventListener("DOMContentLoaded", event => {
let $ = document.querySelector.bind(document);
let options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
$("#currPos").addEventListener("click", getLocation);
function getLocation() {
let geolocation = navigator.geolocation;
if (geolocation) {
geolocation.getCurrentPosition(onGeoSuccess, onGeoError, options);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function onGeoSuccess(position) {
$("#lat").innerHTML = position.coords.latitude;
$("#lon").innerHTML = position.coords.longitude;
}
function onGeoError(error) {
let detailError;
if(error.code === error.PERMISSION_DENIED) {
detailError = "User denied the request for Geolocation.";
}
else if(error.code === error.POSITION_UNAVAILABLE) {
detailError = "Location information is unavailable.";
}
else if(error.code === error.TIMEOUT) {
detailError = "The request to get user location timed out."
}
else if(error.code === error.UNKNOWN_ERROR) {
detailError = "An unknown error occurred."
}
$("#error").innerHTML = `Error: ${detailError}`;
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.