Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created February 14, 2023 06:22
Show Gist options
  • Save w3collective/b089f598e5c1aad3099fc44770c72fa8 to your computer and use it in GitHub Desktop.
Save w3collective/b089f598e5c1aad3099fc44770c72fa8 to your computer and use it in GitHub Desktop.
Using the HTML Geolocation API to display a users location on a map
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Using the HTML Geolocation API to display a users location on a map</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
</head>
<body>
<div id="map" style="height: 500px"></div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert("Geolocation is not supported by this browser");
}
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
getMap(latitude, longitude);
}
function error() {
alert("Unable to retrieve location");
}
function getMap(latitude, longitude) {
const map = L.map("map").setView([latitude, longitude], 5);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);
L.marker([latitude, longitude]).addTo(map);
}
})();
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment