DEV Community

Cover image for Geolocation Tutorial - Get User Location using Vanilla JS
The Dev Drawer
The Dev Drawer

Posted on

Geolocation Tutorial - Get User Location using Vanilla JS

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">
<meta charset="utf-8">
<title>Geolocation Request Tutorial</title>
<link rel="stylesheet" href=""/>
<script src=""></script>
    #map { height: 80vh; display:none; }
    #result { font-size:1.5rem; font-weight:bold; text-align:center; margin-bottom:.5rem; display:none; }
    <button type="button" id="showPosition">Show Position</button>
    <div id="result"></div>
    <div id="map"></div>
<script src="/js/init.js"></script>
Enter fullscreen mode Exit fullscreen mode

Getting Location Permission

class Geolocation {
    // on success
        let result = document.querySelector("#result") // get the result div = "block" // show the result div
        result.innerText = "Lat: " + position.coords.latitude + ", Long: " + position.coords.longitude // display the latitude and longitude

    // on error
        let result = document.querySelector("#result") // get the result div = "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."

        if(navigator.geolocation) { // if the browser supports geolocation
            ) // get the user's location
            let result = document.querySelector("#result")
   = "block"
            result.innerText = "Getting the position information..."
            alert('Your browser does not support geolocation') // if the browser doesn't support geolocation

const showPosition = document.querySelector("#showPosition")
showPosition.addEventListener("click", function (e) {
    let result = document.querySelector("#result") = "block"
    new Geolocation().showPosition() // show the user's location

Enter fullscreen mode Exit fullscreen mode

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 = "block" // show the map container

const map ="map").setView(
    [position.coords.latitude, position.coords.longitude],
) // create a map and set the view to the user's location

const tiles = L.tileLayer(
        maxZoom: 19,
            '&copy; <a href="">OpenStreetMap</a>'
).addTo(map) // add the tiles to the map

const marker = L.marker([
]).addTo(map) // add a marker to the map
Enter fullscreen mode Exit fullscreen mode

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.


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 go wild and have fun with your new geolocation script.

Discussion (0)