Getting Started with Leaflet

Included in this tutorial:

  • Preparing your leaflet page

  • Setting up your first map

Software version in examples: Leaflet 1.9.4

Credits: Steven Dela Cruz Duncan & L. Meisterlin (2025)

 

Welcome to this beginner-friendly tutorial on Leaflet Web Mapping. Leaflet is an open-source JavaScript library for interactive maps. It is lightweight, easy to use, and works seamlessly across devices and browsers.

Related Tutorials:


Preparing your Leaflet page

To start using Leaflet, you need to set up a simple HTML page. This section will guide you through linking the required Leaflet libraries and creating a basic structure for your web map.

Step 1: Open your HTML file

Open your index.html file in Visual Studio Code. If you haven't created one yet, follow the Getting Started with Visual Studio Code to set up your project folder and file structure. Open the index.html file in Visual Studio Code and copy the following code:

 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>My First Leaflet Map</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    
    <!-- Leaflet JavaScript -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    
    <style>
        #map { height: 500px; width: 50%; }
    </style>

</head>
<body>
            <h1>This is my webpage. </h1>
            <div id="map"></div>
</body>
</html>

Inside the <body>, we included a <div> element with the ID map. This will serve as the container where Leaflet will render the map.


Setting up your first map

Now that we have the basic structure, let's initialize the map and add some basic features.

Step 2: Initialize the Map 

Right before the closing the <body> with </body> tag, add the following script to initialize the map:

 
<script>

    // Initialize the map and set its view to a chosen geographical coordinates and zoom level
  
  var map = L.map('map').setView([40.8075, -73.9626], 17);

    // Add a tile layer (OpenStreetMap is used in this example)

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
       
  }).addTo(map);

</script>

full code for this tutorial

Example Output of Initialized Map 

After running the script, use Live Studio to initialize your map, which should look like this. 

initial setup of Leaflet map

 
Previous
Previous

Getting Started in Visual Studio Code

Next
Next

Using the Hotspot Analysis tool for Getis-Ord Gi*