#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

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

Last modified February 14th 2023 | GitHub Source Code [GitHub] | #js

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">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Geolocation API</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 src="script.js"></script>
  </body>
</html>Code language: HTML, XML (xml)

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");
  }    
})();Code language: JavaScript (javascript)

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");
}Code language: JavaScript (javascript)

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 = 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);
}Code language: JavaScript (javascript)

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:

Geolocation Map Marker

Related Posts

#AD Shop Web Developer T-Shirts