Affiliate link
HTML - Geolocation
Geolocation API enable web page to get/track device's location.
HTML Geolocation - Get device's current location
Syntax
getCurrentPosition(success)
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)
Parameters
successerroroptions<script type="javascript">
function showMyLocation() {
const status = document.getElementById('status');
const mapLink = document.getElementById('map-link');
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.text = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.text = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.text = 'Unable to retrieve your location';
}
navigator.geolocation.getCurrentPosition(success, error);
}
document.querySelector('#find-me').addEventListener('click', showMyLocation);
</script>
<body>
<button id="find-me">Show my location</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
</body>Code result
Affiliate link
HTML Geolocation - Get device's updated location
Syntax
watchPosition(success)
watchPosition(success, error)
watchPosition(success, error, options)
<script type="javascript">
function watchMyLocation() {
const status = document.getElementById('status2');
const mapLink = document.getElementById('map-link2');
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.text = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.text = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.text = 'Unable to retrieve your location';
}
navigator.geolocation.watchPosition(success, error);
}
document.querySelector('#watch-me').addEventListener('click', watchMyLocation);
</script>
<body>
<button id="watch-me">Watch my location</button><br />
<p id="status2"></p>
<a id="map-link2" target="_blank"></a>
</body>Code result
Affiliate link
Affiliate link




