If you often use maps on your website, you may be interested in getting the geolocation of your user's location. In this tutorial, we go over how to find the latitude and longitude of your user after asking permission. Once we have those coordinates, we use an open-source map to plot their exact location within a visual interface.
NOTE: This tutorial uses Leaflet + OpenStreetMap but you can use the same methods to integrate Google maps.
View This On YouTube
This simple tutorial will only use 2 files. Your main index.html
and your init.js
.
Creating Our Frontend
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Geolocation Request Tutorial</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"></script>
<style>
#map { height: 80vh; display:none; }
#result { font-size:1.5rem; font-weight:bold; text-align:center; margin-bottom:.5rem; display:none; }
</style>
</head>
<body>
<button type="button" id="showPosition">Show Position</button>
<div id="result"></div>
<div id="map"></div>
</body>
<script src="/js/init.js"></script>
</html>
Getting Location Permission
class Geolocation {
// on success
successCallback(position){
let result = document.querySelector("#result") // get the result div
result.style.display = "block" // show the result div
result.innerText = "Lat: " + position.coords.latitude + ", Long: " + position.coords.longitude // display the latitude and longitude
}
// on error
errorCallback(error){
let result = document.querySelector("#result") // get the result div
result.style.display = "block" // show the result div
if(error.code == 1) { // if the user denied the request
result.innerText = "You have not given permission to access your location."
}else if(error.code == 2) { // if the position is unavailable
result.innerText = "Your location is unavailable."
}else if(error.code == 3) { // if the request times out
result.innerText = "The request to get your location timed out."
}else{ // if something else went wrong
result.innerText = "An unknown error occurred."
}
}
showPosition(){
if(navigator.geolocation) { // if the browser supports geolocation
navigator.geolocation.getCurrentPosition(
this.successCallback,
this.errorCallback
) // get the user's location
let result = document.querySelector("#result")
result.style.display = "block"
result.innerText = "Getting the position information..."
}else{
alert('Your browser does not support geolocation') // if the browser doesn't support geolocation
}
}
}
const showPosition = document.querySelector("#showPosition")
showPosition.addEventListener("click", function (e) {
e.preventDefault()
let result = document.querySelector("#result")
result.style.display = "block"
new Geolocation().showPosition() // show the user's location
})
Once you run the code above, your browser should ask you for permission to use your location. If you accept, it will display your latitude
and longitude
in the #result
div.
If you decline, it will show your error message in the same div.
Adding A Map
In the HTML code we added in the first section, you may have noticed a reference to Leaflet. This is what we are using for the map in this tutorial since it is open-source and free, however, you can simply use Google maps the same way once you get your latitude and longitude.
In your init.js
file, add the following in your successCallback
function.
let mapContainer = document.querySelector("#map") // get the map container
mapContainer.style.display = "block" // show the map container
const map = L.map("map").setView(
[position.coords.latitude, position.coords.longitude],
13
) // create a map and set the view to the user's location
const tiles = L.tileLayer(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}
).addTo(map) // add the tiles to the map
const marker = L.marker([
position.coords.latitude,
position.coords.longitude
]).addTo(map) // add a marker to the map
Place it directly after your last result.innerText
code. Once you run the combined code, you should see a map with a marker with the exact location you are supplying.
Conclusion
It is a simple script and can be used for other things or other scripts, not just a point on a map. Once you have access to your user's location, you can use it to direct them to specific pages or display specific content...so go wild and have fun with your new geolocation script.
Read more articles on DevDrawer
Top comments (0)