Introduction to the Leaflet JavaScript Mapping Library

Leaflet is an open-source JavaScript library for mobile-friendly interactive maps. It is lightweight (around 33 KB) compared to other mapping libraries, and is also comparatively easy to use.

Leaflet is also an integral part of the API used by the commercial service MapBox.

While the Google Maps API is useful for many, if not most, simple web-mapping applications, it locks you into using Google Maps and into Google's way of doing things. Leaflet offers more options and is, arguably, a bit simpler to use.

Open-Source Software

Leaflet is open-source, which means it is:

The traditional proprietary software model (used by companies like Micro$oft or E$RI) involves making money by maintaining monopoly control over their software and services, and charging for the ability to use that software. The advantage of the proprietary business model is that the profits made from the sales are (partially) plowed back into the development of the software, making it feature-rich.

The disadvantage to the proprietary model is that users are locked in to the features that the software company decides to offer and dependent on those companies to fix bugs. Industries tend to move towards standards and vendor lock-in, giving software companies like Micro$oft and E$RI that make industry-standard software great control and profit at the expense of flexibility and cost for their clients. This can also stifle innovation as large software companies have to focus on legacy company needs.

In contrast open-source software is programmed by individuals and businesses who make a contribution to community efforts. Technology companies make their money by selling individualized services to organizations that use the software, rather than making money selling the software itself.

The idea is that technology is better when we are standing on each other's shoulders rather than standing on each other's toes.

The communal aspect of this software means that bugs can be addressed quickly, and companies that need to add features can leverage the efforts of a programmer community broader than their own in-house team. The disadvantage is that many software packages do not have a deep community and do not have the resources to develop and implement the same range of features as their proprietary counterparts.

Open Standards

Standards are rules, protocols and formats for representing data. They are like a common language that permits easy exchange of information with minimal additional processing and errors. For example, the shapefile is a standard defined by ESRI that is well-established and supported by a wide variety of software.

Standards can be defined by common practice (de facto) or by authoritative organizations (de jure) like the International Standards Organization (ISO). Most standards in geospatial technology are de facto because there is no ruling body that totally controls geospatial technology. The shapefile is a de facto standard because the common practice of using shapefiles just emerged with the ubiquity of ESRI software and the fact that ESRI released a description of the standard that permitted other developers to read and write that format. While WGS 84 as a standard for the meaning of latitude and longitude was developed by the US Department of Defense, its common use emerged as a convenience rather than by government decree.

With the rapidly exploding volume of geospatial information, the need for standards is constantly growing. One effort to develop and codify standards is the Open Geospatial Consortium (OGC), a non-profit organzation comprised of members from industry, government and academia. Most of their standards apply to the internal workings of geospatial technology that the general public does not see, the benefits can be more broadly felt in the smooth interoperability of different geospatial technologies. Some example standards include:

Some companies like E$RI choose to use open standards for some aspects of their operations, but incorporate proprietary formats and protocols into many of their products. Proprietary formats and protocols are guarded as company secrets and often not revealed to third party developers. An advantage of proprietary formats and protocols is that they can be adapted more quickly to changing demands and technologies than open standards that often require years for approval among all interested parties. The downside of proprietary for users is vendor lock-in, where user data is trapped in proprietary formats and organizational practices are built around proprietary solutions, requiring the organization to continue to buy products from their vendor even though better and/or cheaper products may be available from other vendors.

A Basic Leaflet Map

To use leaflet, you need to need to include a JavaScript library (leaflet.js) and a CSS stylesheet (leaflet.css). You should download and unzip a copy of the Leaflet files, and place them in a directory on your own server that can be accessed by the script. This protects you from unexpected upgrades that might break your script, or dependency on the free kindness of whoever pays unpkg.com (in the example above) to host the Leaflet code:

<script src="leaflet/leaflet.js"></script>
<link rel="stylesheet" type="text/css" href="leaflet/leaflet.css"/>

L is an object defined in the leaflet library. To create a new map, you call L's map() method. To set the center and zoom level of the new map you then call that map's setView() method.

Note that the lat/long values given as the first parameter to setView() are enclosed in square brackets. That is an example of an array that contains multiple values like objects. Arrays are different from objects in that object properties are named and array elements are not.

var map = L.map("map");
map.setView([40.7484, -73.9857], 12);

The options object is passed as the second parameter to the tileLayer() method. In this case it only has one property that is set to text that is listed at the bottom right corner of the map to indicate where the map came from. Note that text must be enclosed in double-quotes.

var options = { attribution: "(c) OpenStreetMap Contributors" };

The base map is set to map tiles that come from OpenStreetMap, a community-driven web map and geospatial data source similar to Google Maps. OpenStreetMap uses volunteered data that, unlike proprietary Google Maps data, can be freely used as long as credit is given to OpenStreedMap and its contributors. OpenStreetMap contributors have a wide variety of motivations, from an obsession with the act of mapping, to a desire to help areas in the Global South that are often ignored by commercial map data providers.

The syntax for the first tileLayer() parameter is a URL template, and you can read the tileLayer() documentation if you want to know its syntax. The new layer's addTo() method is called to add it to the map.

var layer = L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", attribution)
layer.addTo(map);

There are a variety of freely available base map tile services. See the examples on this map for URL strings to those providers.

This map also includes a single placemarker that is created with L's marker() method. The only parameter in this example is an array with lat/long, but there is a optional second parameter that can be an object containing other options like the icon used for the marker or different behaviors.

Leaflet placemarks are a bit easier to use than Google Maps markers if you want to add text that pops up (what Google calls an infoWindow) when you click on the marker. Note that the popup text can include HTML tags like the line break <br/>

var marker = L.marker([40.7484, -73.9857]);
marker.addTo(map);
marker.bindPopup("Empire State Building<br/>350 5th Ave, New York, NY 10118");
marker.openPopup();

KML Overlays

In addition to the basic functions in the Leaflet library, leaflet supports a significant and growing number of plugin libraries that can be loaded to augment what can be done with Leaflet.

Support for KML layers is part of a set of plugins created by Pavel Shramov. As with the leaflet.js and leaflet.css files, you may want to download a zip file of a plugin, unzip it, and then copy the needed JavaScript (.js) files into a directory on your own server. In this case, support for KML is in the KML.js file:

<head>
<script src="leaflet/leaflet.js"></script>
<script src="leaflet/KML.js"></script>
<link rel="stylesheet" type="text/css" href="leaflet/leaflet.css"/>
</head>

An advantage of using Leaflet over Google for KML is that this plugin renders the polygons directly in browser rather than through a tile server like the Google Maps does. However, if you have a large number of polygons, or if they are highly detailed (such as a high-resolution shapefile of the states in the USA), this can cause poor performance.

Two quirks additional about this plugin:

WMS Layers

Web Map Service (WMS) is an open standard for sharing map images that is commonly used by open-source tile servers. In the case above, the tiles are for an interactive topographic map made available as a WMS service by the USGS for their National Map.

WMS requests are URLs containing parameters in a format specified in the WMS specification. For example, the following is an (ugly) WMS URL:

http://basemap.nationalmap.gov/arcgis/services/USGSTopo/MapServer/WMSServer?
SERVICE=WMS"REQUEST=GetMap"VERSION=1.1.1"LAYERS=0"STYLES="FORMAT=image%2Fpng
"TRANSPARENT=true"HEIGHT=256"WIDTH=256"SRS=EPSG%3A3857
"BBOX=-13071343.332991421,6066042.564711587,-13032207.574509408,6105178.323193595

If you copy that URL into a browser, the following map tile should pop up:

The first parameter to the tileLayer.wms() method is the URL for the WMS server.

The wms_options object passed as the second parmeter to the tileLayer.wms() method has options that are passed to the WMS server. WMS servers often can supply multiple layers, and the name of the one used in this example is 0. WMS servers can often supply images in a variety of different file types - PNG (portable network graphics) is one that gives good clarity with a moderately large file size. The attribution, as before, gives credit at the bottom left of the map to the source of the map contents.

There are a wide variety of publicly-available WMS servers available on the web, although figuring out server URL and appropriate layer ID can require interpreting difficult XML.

For example, clicking the links in the table of WMS services from National Oceanographic and Atmospheric Administration's nowCOAST website make GetCapabilities calls to their WMS server. For this URL, the name of the server is everything before the question mark, which indicates the start of the query string to the server:

GetCapabilities URL:

http://nowcoast.noaa.gov/arcgis/services/nowcoast/analysis_meteohydro_sfc_qpe_time/
MapServer/WMSServer?request=GetCapabilities&service=WMS&version=1.3.0

Server URL:

http://nowcoast.noaa.gov/arcgis/services/nowcoast/analysis_meteohydro_sfc_qpe_time/MapServer/WMSServer?

A WMS server often supports multiple services (layers). For example, the table on the NOAA page lists the different kinds of services. The service with the ID "5" is the 48-Hr Quantitative Precipitation Accumulation in inches, which is listed this way in the GetCapabilities XML:

<Layer queryable="1">
<Name>5</Name>
<Title>Image</Title>
<Abstract>mrms_qpe48hr</Abstract>

WMS servers also usually provide PNG legends, which can be identified in the GetCapabilities XML:

<LegendURL width="124" height="432">
<Format>image/png</Format>
<OnlineResource xlink:href="http://nowcoast.noaa.gov/arcgis/services/nowcoast/
analysis_meteohydro_sfc_qpe_time/MapServer/WmsServer?
request=GetLegendGraphic%26version=1.3.0%26format=image/png%26layer=5" xlink:type="simple"/>
</LegendURL>

The example below floats the legend as an image beside the DIV used for the map. Note that the display type for the map DIV is changed to inline-block so the legend image will sit just to the right of the map.

Also note that the WMS layer is placed on top of an OSM base map. The options for the WML layer include "transparent: true" and "opacity: 0.5" so that the WMS layer is semi-transparent and the base map is visible through the colored areas on the WMS layer.

Image Overlay

Scanned or historical map imagery can be overlaid on top of a map using the imageOverlay() method. The parameters passed include the URL to the image, an array containing the bottom-left and top-right lat/long for the map, and a set of additional options.

The option used above is opacity: 1 means the image completely covers anything below it, zero means it is completely transparent, and the value 0.6 used in this example means it is semi-transparent so you can see the current OpenStreetMap through the historic 1908 map of Downtown Spokane.

Note that the the map image projection needs to be compatible with the spherical Mercator projection used by almost all web maps. If your map covers a small area, this will usually not be an issue, but unless your image is a Mercator projection, large areas like states, countries or continents may be too distorted by the projection to be usable.

Multiple Layer Control

Layer Controls are a useful native feature of Leaflet if you have multiple layers and you wish to give a user control over which layers to show. Note that the layer control is a popup that is activated when you click the layer icon at the top right of the map.

For this example, the layers are all created first, and then the map is created with a layers option that is an array containing all the different layers that will be displayed on the map.

To build the layer control, you need to create two objects. The base_maps object contains properties that are the names of the layers as they will be displayed to the user. The values associated with those names are the layer objects you created earlier.

The overlays object is similar, except it gives layers that will be overlaid on top of the base_maps.

The L.control.layers() method creates the layer, and the addTo() method of the layer adds it to the map.

Note that cartographers like being able to vary base maps, but users to sites that are primarily about getting quick information (like government web maps) rarely change default map settings. Plan your development effort accordingly.

Tutorials, Documentation and PlugIns

The leaflet website is an excellent resource if you need additional tutorials, documentation and/or plugins.