Getting Started with Leaflet.

Leaflet is a lightweight JavaScript library for creating interactive mapping applications. Leaflet is designed with simplicity, usability and perfomance in mind. When creating applications that will use maps in their functionality, We recommend leaflet because of how simple it is and its functionality can be extended with plugins which are in the documentation. In this tutorial, I will go through the basic steps how to set up leaflet, and create a simple web application for mapping.

Below are the steps to set up leaflet.

  • In a new project directory, create a HTML file and name it index.html . Fill the file with the basic HTML code, add a div tag with id map. You can copy the following code:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Leaflet Tutorial</title>
    </head>
    <body>
      <div id="map">
    
      </div>
    </body>
    </html>
    
  • Add a css file named style.css in the same directory as the index.html file. Fill the file with the following css code. Do not skip this step.

#map{
    height:600px;
}
  • Remember to add a reference to the created css file. To do this, add the following line on the head section of the index.html
<link rel="stylesheet" type="text/css" href="style.css" />
  • Now, we need to set-up the leaflet cdns for CSS and JavaScript to be able to serve our map.

  • copy the following two lines and add them in the head section of your index.html

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
     integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
     crossorigin=""/>
    
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
     integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
     crossorigin=""></script>
    
  • The next step is to initialize the map and add data to it.

  • Copy the following JavaScript code and place just before the closing body
<script>
// Initialize and assign a variable map, set the view centered on a location in Nairobi witha zoom level of 7
var map = L.map('map').setView([-1.2921, 36.8219], 7);

// Adding the tileLayer
var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy;<href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>contributors'
        }).addTo(map);
</script>
  • Open the index.html file in a browser and confirm that the map is displaying.

Adding GeoJSON to the map

  • Go to this link https://geojson.io and create a few random points. Preferably in the area around Nairobi. Alternatively, you can download this file from pastebin using this direct link and place it in the same folder as your index.html file. https://pastebin.com/dl/jfV2J3UK
  • The following image shows some random points selected in https://geojson.io
  • If you decided to generate your own, generate at least 20 random points, create a data.json file and assign the variable data to the JavaScript object, similar to the one on this file in the pastebin: https://pastebin.com/jfV2J3UK or the code below the following image.

geojson.png

var data = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.82891845703125,
          -1.2839196334992269
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.84539794921875,
          -1.2962761196418089
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.80419921875,
          -1.307259612275665
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.7767333984375,
          -1.2695036575538965
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.824798583984375,
          -1.3141242707983072
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.87835693359375,
          -1.2605794416293021
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.890716552734375,
          -1.2798007914843985
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.85020446777344,
          -1.2502822314149136
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.8701171875,
          -1.2894114125257745
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.81449890136719,
          -1.2544011203660779
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.85432434082031,
          -1.26195239992168
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.80351257324219,
          -1.263325357489324
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.800079345703125,
          -1.2736225160659695
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.85157775878906,
          -1.3079460789741424
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          36.85569763183594,
          -1.271563087631464
        ]
      }
    }
  ]
}
  • Add the following script tag to reference to the newly created data.json file.

    <script type="text/javascript" src="data.json"></script>
    
  • Add the following JavaScript code to the first script tag: Here we are adding the GeoJSON data to the map as a layer.

    var data_points= L.geoJSON(data
    ).addTo(map);
    
  • Open the index.html file on the browser. To confirm that this works.

  • You will now see the GeoJSON data displayed as markers on the map. You can compare it with your points on https://geojson.io

Adding Layer controls

  • To add layer controls for the tile layers and our GeoJSON data, add the following JavaScript code:
var baseMaps = {
      "Open Street Map":osm,
    };
var data = {
      "Our Points":data_points,
    };

    L.control.layers(baseMaps, data).addTo(map);

Adding Marker Clusters for our point data

  • Marker Clusters are used to make viewing the map easier, especially in places with a high number of data points per area in the map. When the user zooms out on many markers, the markers gather into clusters making the user to view the map easier.
  • To add Marker Clusters in our map for our points, Follow the following steps:
  • Add the following lines in the head section of the index.html file. This is a CDN for a plugin that is referenced on the official Leaflet documentation for creating Marker Clusters. There are many plugins for this and you can go and check them.
<link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css">
<link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css">
<script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster.js"></script>
  • Add the following lines of code to the script tags. These lines declare a variable for a marker cluster and the addLayer() method takes the data to be clustered in a Marker Cluster as an argument.

var markers = L.markerClusterGroup();
markers.addLayer(data_points);
map.addLayer(markers);
  • The following is the full index.html file:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Leaflet Tutorial</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>
   <!-- Make sure you put this AFTER Leaflet's CSS -->
 <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
   integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
   crossorigin=""></script>
   <link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css">
   <link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css">
   <script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster.js"></script>
</head>
<body>
    <div id="map">

    </div>
  <script type="text/javascript" src="data.json"></script>
    <script type="text/javascript">

    // OnEachFeature Function
    function onEachFeature(feature, layer) {
        layer.bindPopup(String(feature.geometry.coordinates));
      }


        var map = L.map('map').setView([-1.2921, 36.8219], 7);

    // Adding the tileLayer
        var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

    // Adding the geoJSON
    var data_points= L.geoJSON(data,
    {
      onEachFeature:onEachFeature
    }).addTo(map);

    var baseMaps = {
      "Open Street Map":osm,
    };
    var data = {
      "Our Points":data_points,
    };

    L.control.layers(baseMaps, data).addTo(map);

    // Declare the cluster group and add markers to the clusters
    var markers = L.markerClusterGroup();
    markers.addLayer(data_points);
    map.addLayer(markers);
    </script>
</body>
</html>
  • Finally, open the html file on the browser and see the output. The marker clusters should be created and the screen should be similar to mine here on this demo