Skip to content

Adding a new Leaflet JavaScript Plugin

The optional part of the previous lab was to change the basemap.

Taking that one step further we can add brand-new functionality to our maps.

While the Leaflet provider is a plug-in of basemaps for Leaflet, there are many plugins that we can use to add extra functionality to our mapplication in JavaScript as well. Here are some examples:

Visualizations

General JavaScript Functions

To keep things simple, we will add a cluster marker functionality to our Leaflet map. Clustering makes it easier to see when multiple points are in the same area.

With just a few changes our map will look as follows:

As with when we first used Leaflet we need to include the library, so in our html add the following lines:

index.html

        <!-- Cluster Marker's CSS -->
        <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css" />
        <!-- Cluster Marker's JavaScript -->
        <script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster.js"></script>

Next, let’s read the documentation on how to use the cluster maker:

Judging from this code, we might be able to simply change our group layers for the markers!

Head over to our init.js file and find the following lines for our group layers:

js/init.js
let vaccinated = L.featureGroup();
let nonVaccinated = L.featureGroup();

Change it to:

js/init.js
let vaccinated = L.markerClusterGroup();
let nonVaccinated = L.markerClusterGroup();

And… wow that’s it!

This flexibility is what makes opensource tools and plugins so great! However, be warned that not all plugins will be as simple to plug and play.

Congrats!

After you’ve made this change the time has come to make a pull request!