Geolocation API quick start
The Geolocation API can request the current position with a small amount of JavaScript. The browser asks the user for permission before it returns location data.
What you will learn
- How to request the current position
- How to read latitude and longitude
- Why the result arrives through an asynchronous callback
HTML
<dl>
<dt>Latitude</dt><dd id="latitude">-</dd>
<dt>Longitude</dt><dd id="longitude">-</dd>
</dl>
JavaScript
navigator.geolocation.getCurrentPosition((position) => {
document.querySelector('#latitude').textContent = position.coords.latitude;
document.querySelector('#longitude').textContent = position.coords.longitude;
});
Call getCurrentPosition() after a user action when possible. The browser may reject the request, and production pages normally need HTTPS.
How the callback works
The method does not return a position immediately. It asks the device for a result, then calls the function you provide. The position.coords object contains latitude, longitude, accuracy, and other values.