"How to Create an Interactive Web Map Using Leaflet.js & OpenStreetMap"

 Introduction

In today's digital world, interactive web maps are essential for displaying geographic data in an engaging way. Leaflet.js, a lightweight JavaScript library, combined with OpenStreetMap (OSM), allows developers and beginners to build powerful interactive maps with ease.

This guide walks you through creating an interactive web map step-by-step using Leaflet.js and OpenStreetMap. Whether you're a GIS developer or a beginner exploring web mapping, this tutorial will provide you with a solid foundation.

What is Leaflet.js?

Leaflet.js is an open-source JavaScript library used for creating interactive maps. It is lightweight, mobile-friendly, and supports custom markers, popups, layers, and tile providers.

Why Use Leaflet.js?

  • Lightweight (~42KB gzipped)

  • Open-source and free

  • Works across all devices

  • Easy integration with OpenStreetMap and other tile providers

  • Extensive plugins for additional functionality

Setting Up the Project

Step 1: Create an HTML File

Create a new HTML file (index.html) and add the Leaflet.js library and CSS.

       HTML: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Web Map</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
</head>
<body>
    <div id="map" style="height: 500px;"></div>
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
</body>
</html>

Step 2: Initialize the Map

Add the following JavaScript to initialize the map:

       HTML:

<script>
    var map = L.map('map').setView([51.505, -0.09], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);
</script>

Explanation:

  • L.map('map') initializes the map inside the <div id="map">.

  • .setView([lat, lng], zoom) sets the default map center and zoom level.

  • L.tileLayer(...) loads OpenStreetMap tiles.

  • .addTo(map) adds the layer to the map.

"Leaflet.js map of London"

Adding Markers & Popups

Step 3: Add a Marker

Markers help highlight locations on the map.

          HTML:

<script>

    var marker = L.marker([51.5, -0.09]).addTo(map);

    marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();

</script>

"Map showing London marker with a popup displaying the message 'Hello world!' for interactive map features."

Adding Customs Icons

Step 4: Add a Custom Marker Icon

You can customize markers using an icon.

        HTML:

<script>
    var customIcon = L.icon({
        iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
        iconSize: [38, 95],
        iconAnchor: [22, 94],
        popupAnchor: [-3, -76]
    });
    L.marker([51.5, -0.09], {icon: customIcon}).addTo(map)
        .bindPopup("Custom Icon Marker");
</script>

"Map featuring a custom green leaf icon marker for a unique, nature-inspired location."

Adding GeoJSON Data

Step 5: Display GeoJSON Data

GeoJSON is a format for encoding geographic data.

        HTML:

<script>

    var geojsonFeature = {

        "type": "Feature",

        "properties": {

            "name": "GeoJSON Point",

            "popupContent": "This is a GeoJSON marker!"

        },

        "geometry": {

            "type": "Point",

            "coordinates": [-0.09, 51.5]

        }

    };

    L.geoJSON(geojsonFeature).addTo(map);

</script> 

"Map showing a GeoJSON point marker indicating a specific geographical location."

Adding Multiple Markers

Step 6: Add Multiple Markers

HTML:
<script>
    var locations = [
        [51.5, -0.09],
        [51.51, -0.1],
        [51.49, -0.08]
    ];
    locations.forEach(function(loc) {
        L.marker(loc).addTo(map);
    });
</script>

 

"Map displaying multiple markers across London, highlighting various locations and points of interest."


Adding Layer Control

HTML: 

<script>
    var streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
    var satellite = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png');
    var baseMaps = {
        "Street Map": streets,
        "Satellite": satellite
    };
    L.control.layers(baseMaps).addTo(map);
</script>

"Map with layer control toggle to switch between Street Map and Satellite views."

Adding a Search Box

Use Leaflet Control Search Plugin

        HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-search/2.9.7/leaflet-search.min.js"></script>

<script>

    var searchControl = new L.Control.Search({

        layer: map,

        propertyName: 'name',

        marker: false,

        moveToLocation: function(latlng, title, map) {

            map.setView(latlng, 14);

        }

    }).addTo(map);

</script> 

"Map featuring a search box for easily finding and navigating to specific locations."

Conclusion

Congratulations! You’ve successfully created an interactive web map using Leaflet.js and OpenStreetMap. You learned:

  • How to initialize a map

  • How to add markers, popups, and custom icons

  • How to integrate GeoJSON data

  • How to add multiple markers & layers

  • How to enhance functionality with search

Call to Action

🚀 Want more GIS tutorials? Subscribe to our newsletter and stay updated with the latest GIS trends!

Related Resources:

Happy mapping! 🌍

Comments