DEV Community 👩‍💻👨‍💻

Michael Burrows
Michael Burrows

Posted on • Originally published at

Using the HTML Geolocation API to display a users location on a map

In this tutorial we'll be using the HTML Geolocation API to display the current location of a user on a map. While this example is quite simple it's provides solid foundation for creating more complex location-aware web sites and applications.

Let's get started by creating a new HTML file with the following markup:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Geolocation API</title>
    <link rel="stylesheet" href="" />
    <div id="map" style="height: 500px"></div>
    <script src=""></script>
    <script src="script.js"></script>
Enter fullscreen mode Exit fullscreen mode

You'll notice we're loading Leaflet an open-source JavaScript library for creating interactive maps. When used in conjunction with OpenStreetMap it's a powerful alternative to the Google Maps API.

Next create a new JavaScript file called called script.js. All modern browsers support Geolocation but we'll still check that the current users browser is supported and display an alert message if that's not the case:

(() => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    } else {
        alert("Geolocation is not supported by this browser");
Enter fullscreen mode Exit fullscreen mode

If Geolocation is supported we use the getCurrentPosition method to return the users current position. If successful the latitude and longitude are passed to a success() function otherwise the error() function is called:

function success(position) {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  getMap(latitude, longitude);
function error() {
  alert("Unable to retrieve location");
Enter fullscreen mode Exit fullscreen mode

With the users latitude and longitude captured we can create a getMap function that uses Leaflet to display a map with a marker of the users current location:

function getMap(latitude, longitude) {
  const map ="map").setView([latitude, longitude], 5);
  L.marker([latitude, longitude]).addTo(map);
Enter fullscreen mode Exit fullscreen mode

Open the HTML file in a browser (you'll need to allow the file to know you location). If everything worked correctly you should see a map with your current location marked:

Alt Text

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.