Created
February 14, 2023 06:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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/leaflet@1.7.1/dist/leaflet.css" /> | |
</head> | |
<body> | |
<div id="map" style="height: 500px"></div> | |
<script src="https://unpkg.com/leaflet@1.7.1/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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/geolocation-api-map/