Getting Started with Leaflet
To get started with Leaflet, we have to include it in our HTML document by adding these two lines in the header:
Next, we’ll create the
div element that will contain our map, and set the container to a defined height:
Setting Up the Map
To add the map to the page, all we need to do is add this line of code to our script file:
This will create a map centered at the chosen geographical coordinates and set to a zoom level.
If we look at our webpage, we should see something like this:
Okay…the map is there, but not really there. All we see is this grey screen. This is because we haven’t added a tile layer yet. The tile layer is what actually renders the contents of the map. To add a tile layer, we have to set the URL template for the tile images, the attribution text, and the maximum zoom level of the layer:
There are a lot of different URLs we can use for our tiles, and this website has a great assortment of tile layers plus the code to include it in your project!
Note that some tile providers require an access token to use.
Now if we look at our webpage, we should see the Bay Area! Our map already comes with basic pan and zoom controls, so we don’t have to worry about adding that manually.
Adding Markers, Circles, and Polygons
Leaflet makes it incredibly easy to add various different markers and shapes to your map. Lets say you want to put markers on the three major airports serving the Bay Area:
Adding a circle to the map is almost the same as adding a marker, except we pass in a second argument that specifies the radius of the circle (in meters) and how the circle will look on the map. We’ll add a circle highlighting the Golden Gate Bridge:
And finally, we’ll add some polygons outlining Mt. Diablo in the East Bay:
Simple as that!
Our map looks nice, but if someone who isn’t familiar with the Bay Area looks at this, they may not know what these markers mean. That’s where popups come in. Leaflet allows us to attach information to our markers using the
As you can see, we can even put HTML in our popup! Now whenever we click on one of our objects, we get a popup displaying the information we attached to our object.
Here is the full code for our basic map:
Adding an interactive map to your web application can be an incredibly useful tool. Whether you need to display the location of your business, or need to track the path of a storm, Leaflet has got you covered. What I covered in this blog is just barely scratching the surface of the potential of Leaflet. If you are interested in learning more about Leaflet, I have linked the full documentation at the end of the blog. There is also a neat Python library called Folium that allows you to generate Leaflet maps, which is how I made the below image. The documentation to Folium is also linked at the end of the blog.
Hope this helps!
This reference reflects Leaflet 1.7.1. Check this list if you are using a different version of Leaflet. UI Layers…