Recipe 14.3
Getting the Device Location
Demo
Getting location...
Loading...
Your position is:
- Latitude:
- Longitude:
Code
JavaScript
const loader = document.querySelector('#loader');
const results = document.querySelector('#results');
navigator.geolocation.getCurrentPosition(position => {
loader.classList.add('d-none');
console.log(position);
document.querySelector('#latitude').textContent = position.coords.latitude;
document.querySelector('#longitude').textContent = position.coords.longitude;
results.classList.remove('d-none');
}, error => {
// Either the user denied permission, or the device location could not
// be determined.
console.log(error);
});
HTML
<div id="loader" class="d-flex flex-column align-items-center">
<div>Getting location...</div>
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div id="results" class="d-none">
<h2>Your position is:</h2>
<ul>
<li>Latitude: <span id="latitude"></span></li>
<li>Longitude: <span id="longitude"></span></li>
</ul>
</div>