How to get latitude and longitude from a click event on Open Street Map

Narges Mirzaaghaei
2 min readOct 17, 2022

--

In many web applications, it’s common to store geographic points. For example, suppose we have a form where the user is supposed to enter his address and put his location on the map.

you can get the geographic points in several simple steps.

The video tutorial is also available. You can watch it or continue reading.

In this tutorial, we have a map that whenever the user clicks on the map, a marker is added at that location, and the geographical points are displayed in the inputs.

To get started, I created a simple map using leaflet.js, which you can see in the image below. If the code isn’t clear to you, I explained it in one of my previous articles.

Feel free to read if necessary: How to embed Open Street Map in a webpage (like Google Maps)

create simple map using leaflet js

The next step is adding a click event to watch for when the user clicks on the map and add a marker where the user clicked:

map.on('click', (event)=> {    L.marker([event.latlng.lat , event.latlng.lng]).addTo(map);})

If you want to have only one marker, you must first check if there’s a marker and remove it:

let marker = null;map.on(‘click’, (event)=> {    if(marker !== null){        map.removeLayer(marker);    }marker = L.marker([event.latlng.lat , event.latlng.lng]).addTo(map);})

The last step is to show the geographical points in the inputs:

document.getElementById(‘latitude’).value = event.latlng.lat;document.getElementById(‘longitude’).value = event.latlng.lng;

Try out the code in the following demo:

Here are some other articles you may enjoy:

How to customize the OpenStreetMap marker icon and binding popup

How to display multiple locations on the map and show related information on user hover(like booking.com)

--

--