Map libraries comparison: Leaflet vs Mapbox GL vs OpenLayers – trends and statistics

When you need to add a map to your application, the first question that pop-ups in your head is “Which map library to use?”. If you start to google, you’ll find out soon that at the moment the Leaflet, Mapbox GL, OpenLayers are the most popular libraries for displaying interactive maps on a web page.

In this article, we want to compare the libraries and check actual trends and statistics. So you can choose the most promising option for you.

We used NPM Trends and Google Trends to get the data and create beautiful visualizations.

Leaflet vs Mapbox GL vs OpenLayers

LeafletMapbox GLOpenLayers
The open-source JS library for interactive maps. A simple interface, great documentation, and a huge community allow you to get results and solve your tasks quickly.
Unfortunately, not developed actively any longer.
Powerful and effective SDK for web maps developed by Mapbox. As Leaflet library creators developed Mapbox GL now, you can see some similarities between 2 libraries. However, Mapbox GL gives you more opportunities, data visualization options and opens the vector maps world for you.Familiar with GIS technologies? Then OpenLayers can be the perfect option for you! The OpenLayers is not only about displaying maps, but also visualizing and analyzing geographical data. It could be a bit more complicated at the beginning but allows you to create more powerful solutions.
Vector maps support
The core functionality of Leaflet doesn’t have vector tiles support. Nevertheless, you can visualize vector tiles by using external plugins. For example, Mapbox GL Leaflet.
Vector maps support
Mapbox is a pioneer in vector maps technologies. The Mapbox Style Specification for vector maps, which is very popular now and used by Geoapify as well, is natively supported by Mapbox GL.
Vector maps support
OpenLayers has native support for vector maps but the ol-mapbox-style plugin is required to create a map with Mapbox Style Specification.
JSFiddle code sampleJSFiddle code sampleJSFiddle code sample

NPM trends for the map libraries

The number of downloads for npm packages gives a great indication of how popular each library is. Here is npm trends statistics for the last 12 month:

npm trends: Leaflet, Mapbox GL, Openlayers

And the charts look really interesting! After absolute leadership Leaflet losing to Mapbox GL in February 2020. In comparison with other map libraries, OpenLayers looks stable. And if we check the statistics for OpenLayers only, we can prove that:

npm trends: OpenLayers

Statistics from GitHub show us how many times a library was “stared”:

GitHub statistics: Leaflet, Mapbox GL, Openlayers

And here we see that Leaflet is 5 times more popular at the moment than Mapbox GL, and 4 times more popular than OpenLayers.

Google Trends for the map libraries

Google search keywords trends are another good measure of popularity. However, here we’ve faced with a problem. While “Leaflet” and “OpenLayers” are unique names, “Mapbox GL” is often googled as “Mapbox”. So we decided to add both “Mapbox GL” and “Mapbox” to give you an overview:

The chart shows that interest in each library more or less stays on the same level. In other hands, statistics by regions provide some interesting results as well:

Map libraries comparison by region

Leaflet leads the keywords list in almost all countries. However, Mapbox/Mapbox GL is popular in China, the United States, Belorus, and Canada. And OpenLayers is in request in South Korea, Croatia, and Finland.

Conclusions

It’s always a matter of taste when you are trying to choose the best from the good ones. Nevertheless, we hope that the numbers and charts we gave you in this article will help you to make the right decision.

Leaflet, Mapbox GL, and OpenLayers code samples

We’ve created code samples to help you develop a custom map for your website. Visit the Geoapify Documentation page to learn how to add a map to your React-, Angular-, or Vue-webapp.

Geoapify offers map tiles that can be used with all the libraries. We provide vector and raster maps of different styles and colors. Learn more about Geoapify Map Tiles.

Angular + Leaflet: step by step tutorial to add a map

This tutorial helps you to create an Angular-based application and add a Leaflet map as a component. In our tutorial, we provide a way to use the Leaflet library without additional components. Moreover, we prepared an Angular-project for you that contains already a component skeleton for the map component.

We use Geoapify map tiles for the tutorial. You can choose between different map styles and colors there. Check the Geoapify Maps Playground that contains Live demo and code samples.

We use Mapbox style specification, which describes how the map is rendered, tile server locations, and provides values for map settings. For example, minimum, and maximal zoom levels.

Before you start

Step 1. Create an Angular project

You can use the Angular project template we’ve prepared for you or create a new one with Angular CLI. The project template contains already a component for a map:

  • Download or clone the GitHub repository
  • Switch to the project folder: cd angular-based-project
  • Run npm install to install libraries and dependencies
  • Run ng serve for a dev server
  • Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Step 2. Display a map with Leaflet

Install Leaflet + Mapbox GL plugin

By default, Leaflet doesn’t support vector tiles and Mapbox Style specifications. Therefore you need to install the Mapbox GL Leaflet plugin together with Leaflet to generate a map from style.json:

npm i leaflet mapbox-gl mapbox-gl-leaflet
Install Leaflet + Mapbox GL types

Type definitions will allow you to utilize Leaflet and Mapbox types in your code. Moreover, some IDEs provide code completion when the types are available:

npm i @types/leaflet @types/mapbox-gl-leaflet -dev
Add Leaflet and Mapbox styles

Leaflet and Mapbox styles are required to render a map and it’s elements correctly. We recommend you to add styles to the angular.json:

"projects": {
    "angular-project": {
      ...
      "architect": {
        "build": {
          "options": {
            ...
            "styles": [
              "src/styles.scss",
              "node_modules/mapbox-gl/dist/mapbox-gl.css",
              "node_modules/leaflet/dist/leaflet.css"
            ],
            "scripts": []
          },
          ...
        }
      }
    }
}

You will need to restart the dev server to apply changes from angular.json.

Add a Leaflet map to an Angular-component

Open MyMapComponent if you use our template or create a new component.

  • Remove placeholder and create ViewChild for the div element. Add ngAfterViewInit() lifecycle hook that is called after Angular has fully initialized a component’s view:
<div class="map-container" #map></div>
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
  }
}
  • Add a Leaflet map to the component:
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import  * as L from 'leaflet';
import 'mapbox-gl-leaflet';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  private map: L.Map;

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    const myAPIKey = "YOUR_API_KEY_HERE";
    const mapStyle = "https://maps.geoapify.com/v1/styles/osm-carto/style.json";

    const initialState = {
      lng: 11,
      lat: 49,
      zoom: 4
    };

    const map = new L.Map(this.mapContainer.nativeElement).setView(
      [initialState.lat, initialState.lng],
      initialState.zoom
    );

    // the attribution is required for the Geoapify Free tariff plan
    map.attributionControl
      .setPrefix("")
      .addAttribution(
        'Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>'
      );

    L.mapboxGL({
      style: `${mapStyle}?apiKey=${myAPIKey}`,
      accessToken: "no-token"
    }).addTo(map);
  }
}

Build the application

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

More code sample

Find more Live demos, JSFiddle samples and Code samples on the Geoapify API Documentation page.

React + Leaflet: project template and step by step tutorial

This tutorial helps you to create a React-based application with a Leaflet map. We’ve prepared for you a project template and instructions to develop a Map app from scratch.

We use Geoapify map tiles and Mapbox Style specification to create a map. So at the end of the tutorial, your application will be able to render both vector and raster maps with the Leaflet library.

Before you start

Step 1. Create a React project

We’ve prepared a React-based project template for you. The project already contains a component to visualize a map and uses for Sass3 CSS pre-processor:

  • Download or clone the GitHub repository
  • Switch to the project folder: cd react-based-project
  • Run npm install to install libraries and dependencies
  • Run npm start to start the server
  • Open http://localhost:3000 to view the page in the browser

As the second option, you can generate a React project by yourself with Create React App.

Step 2. Display a map with Leaflet

Install Leaflet + Mapbox GL plugin

By default, Leaflet doesn’t support vector tiles and Mapbox Style specifications. You need to install the Mapbox GL Leaflet plugin together with Leaflet to generate a map from style.json:

npm i leaflet mapbox-gl mapbox-gl-leaflet
Add Leaflet and Mapbox styles

You need to import styles to display a map and it’s elements correctly. You can add the styles to the index.scss file:

@import '~mapbox-gl/dist/mapbox-gl.css';
@import '~leaflet/dist/leaflet.css';
Add a map to a React-component

We already prepared a React-component for you – “src/components/my-map.jsx”:

 
import React, { useEffect } from 'react'; 
import './my-map.scss';

function MyMap() {

  useEffect(() => {
    console.log('This is called when the component is mounted!');
  }, []);

  return (
    <div className="map-container">
      <div className="placeholder">
        <span className="placeholder-text">The map will be displayed here</span>
      </div>
    </div>
  )
}

export default MyMap;

Create one if you’ve generated a project with Create React App. Use can use the MyMap component as an example.

  • Remove the placeholder and add the element reference
  • Make the useEffect() function to be called when the element is ready:
import React, { useEffect } from 'react';
import './my-map.scss';

function MyMap() {
  let mapContainer;

  useEffect(() => {

  }, [mapContainer]);

  return (
    <div className="map-container" ref={el => mapContainer = el}>
    </div>
  )
}

export default MyMap;
  • Add a Leaflet map to the component:
import React, { useEffect } from 'react';
import './my-map.scss';
import L from 'leaflet';
import {} from 'mapbox-gl-leaflet';

function MyMap() {
  let mapContainer;

  useEffect(() => {
    const initialState = {
      lng: 11,
      lat: 49,
      zoom: 4
    };

    const map = L.map(mapContainer).setView([initialState.lat, initialState.lng], initialState.zoom);

    // the attribution is required for the Geoapify Free tariff plan
    map.attributionControl.setPrefix('').addAttribution('Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>');

    var myAPIKey = 'YOUR_API_KEY_HERE';
    const mapStyle = 'https://maps.geoapify.com/v1/styles/osm-carto/style.json';

    const gl = L.mapboxGL({
      style: `${mapStyle}?apiKey=${myAPIKey}`,
      accessToken: 'no-token'
    }).addTo(map);
  }, [mapContainer]);

  return (
    <div className="map-container" ref={el => mapContainer = el}>
    </div>
  )
}

export default MyMap;

Note! You may require to restart the development server to apply all changes.

Build the application

Run npm run build from the application directory. This builds the app for production to the build folder.

More code sample

Find more Live demos, JSFiddle samples and Code samples on the Geoapify API Documentation page.

Leaflet vs OpenLayers. What to choose?

The first step you do when creating a map from scratch is choosing a client mapping library. There are many JavaScript libraries, which allows building a custom map. In this article, we would like to compare 2 widely used mapping libraries: Leaflet vs OpenLayers.

Leaflet

Leaflet holds the leading position among open-source JavaScript libraries for interactive maps. Developed originally by Vladimir Agafonkin and maintained by a big contributes of the community. Moreover, the library is completely free to use and distributed under the BSD-2 Clause license.

https://leafletjs.com

OpenLayers

OpenLayers is a powerful open-source JavaScript library for dynamic maps. It provides a rich API which allows creating simple as well as very complex map applications. The same as Leaflet, it’s free to use and distributed under the BSD 2-Clause license.

https://openlayers.org/

Is quickstart possible?

Leaflet

The Leaflet is designed as easy-to-use and light-weight library. So you can start to develop a map just by copy & paste from the QuickStart tutorial.

OpenLayers

The OpenLayers offers more functionality than Leaflet and requires more time to start. For example, you need to use projections, just to create a simple map.

Moreover, it may also confuse you if you have already experience with other map libraries, that coordinates in OpenLayers not in LatLon format, but in LonLat. Which is by the way correct from GIS point of view.

Maintenance

Leaflet

More than 600 contributes. As a result, releases at least every half year.

OpenLayers

About 240 contributors. Consequently, releases every 3-4 months.

Documentation

Leaflet

The Leaflet has well-structured documentation with a lot of examples and tutorials. In addition, great API documentation allows you to quickly find the functionality required.

However, the basic documentation contains only basic examples. So you have to research on the Internet if you need to learn more.

OpenLayers

The documentation contains QuickStart’s, tutorials and a lot of examples. But, unfortunately, some of them already outdated.

The API documentation is well-structured, but as it’s very large, you may be lost there at begin.

Leaflet and OpenLayers community

Leaflet

The Leaflet is the most popular JavaScript library for maps. So it has a huge community. The lack of example in the official documentation website is refined by many examples from the community.

“leaflet stackoverflow” google request returns 398.000 results.

OpenLayers

As the library is used mainly for complex GIS applications development. So the OpenLayers community is smaller than Leaflet community.

“openlayers stackoverflow” google request returns 52.700 results, consequently.

Flexibility and Power

Leaflet

It contains all the features the most developers ever need by building a map. Furthermore, the additional power is added by Leaflet plugins.

OpenLayers

The power and flexibility are the two most strong characteristics of OpenLayers. The library has all the required features in the core functionality.

Supported GIS formats

Leaflet

The core functionally supports only the GeoJSON format. Nevertheless, support for other formats, like CSV, WKT, TopoJSON, GPX, provided by plugins.

OpenLayers

OpenLayers supports GeoJSON, GeoRSS, KML, GML, and map data from any source using OGC-standards as WMS or WFS.

Amount of code

Leaflet

The Leaflet is designed to be able to achieve the desired result with a minimal amount of code.

For example, a simple map with a marker uses only 3 classes:

var osmLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	maxZoom: 18,
	attribution: '© <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors'
});

var map = L.map('map').setView([51, 12], 12).addLayer(osmLayer);
L.marker([51, 12]).addTo(map);
OpenLayers

More code with OpenLayers. However, the code looks more structured and provides better MVC-separation.

The same example with OpenLayers has 6 classes:

var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
var position = new OpenLayers.LonLat(12, 51).transform(fromProjection, toProjection);
 
map = new OpenLayers.Map("map");
map.addLayer(new OpenLayers.Layer.OSM());
map.setCenter(position, 12);
 
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);

var marker = new OpenLayers.Marker(position);
markers.addMarker(marker);

Leaflet vs OpenLayers summary

Leaflet

Use Leaflet if you are developing just a map, but not a complicated GIS application. Similarly, if the most complex data you deal with is GeoJSON and you do not need to deal with projections.

In the other hand, if you are new in maps world and not a GIS expert, Leaflet may save you a lot of time.

Switch to OpenLayers when you have to use a lot of plugins to make it work.

OpenLayers

Using projections, different Geo data sources, developing integration with other GIS applications? Then OpenLayers will be the right choice!

Geoapify provides maps and components

Geoapify offers maps and map components to create a custom map. Even if “Leaflet vs OpenLayers” is more a matter of taste, both Leaflet and OpenLayers could be used with our map tiles. Certainly, we provide different map designs for you. So you are able to setup “look&feel” for your custom map.

Our APIs, for example, Geocoding, Routing and others, will help you to build interactive and useful map!

Create custom map marker icon with Leaflet

In our previous article, we mentioned two icon sets you can use for free as a map marker icon. In this article, we would like to show you how to create amazing and easy to style map marker pins with Material Design or Awesome icons only with HTML and CSS and add them to your map with Leaflet library.

Almost all mapping libraries allow you to customize marker icons. For example, you can set a ready-to-use image or add an HTML object as a marker icon.

You can generate a Marker Icon with our new Marker Icon API or create it step by step by yourself by following the instructions below.

Create a Leaflet marker with DivIcon

The Leaflet library has a possibility to set up a map marker icon, its size, a position as well as marker shadow icon. Moreover, the extended class from map icon DivIcon allows specifying the div element as a marker icon.

We will focus on DivIcon element and show you how to create beautiful marker icons only with HTML and CSS.

There are a few things you need to know before you start to create a custom marker with DivIcon. Firstly, by default, the Top-Left corner of the icon is bound to the location. To make the pin point to the location you need to specify iconSize and iconAnchor when creating an icon. For example:

var icon = L.divIcon({
        ...
        iconSize: [30, 42],
        iconAnchor: [15, 42] // half of width + height
    });

Secondly, if you rotate a pin element in CSS, keep in mind that the result icon size may be different than pin element size. In our example, we rotate the element to 45 degrees, the height of the result element is 30px √2 = 42px

Create a marker icon with Material Design icon

You can create a map marker with Material Design icons that way:

icon = L.divIcon({
        className: 'custom-div-icon',
        html: "<div style='background-color:#c30b82;' class='marker-pin'></div><i class='material-icons'>weekend</i>",
        iconSize: [30, 42],
        iconAnchor: [15, 42]
    });
    
L.marker([53, 12], { icon: icon }).addTo(map);
.marker-pin {
  width: 30px;
  height: 30px;
  border-radius: 50% 50% 50% 0;
  background: #c30b82;
  position: absolute;
  transform: rotate(-45deg);
  left: 50%;
  top: 50%;
  margin: -15px 0 0 -15px;
}
// to draw white circle
.marker-pin::after {
    content: '';
    width: 24px;
    height: 24px;
    margin: 3px 0 0 3px;
    background: #fff;
    position: absolute;
    border-radius: 50%;
 }

// to align icon
.custom-div-icon i {
   position: absolute;
   width: 22px;
   font-size: 22px;
   left: 0;
   right: 0;
   margin: 10px auto;
   text-align: center;
}

Create a marker icon with Awesome Font

Almost the same way you create map marker icons from Awesome Font. But with one difference – you need to adjust the icon size. For example:

icon = L.divIcon({
	className: 'custom-div-icon',
        html: "<div style='background-color:#4838cc;' class='marker-pin'></div><i class='fa fa-camera awesome'>",
        iconSize: [30, 42],
        iconAnchor: [15, 42]
    });
.custom-div-icon i.awesome {
    margin: 12px auto;
    font-size: 17px;
 }
Find the working example of the code here – https://jsfiddle.net/a08oek3w/2/

Geoapify offers maps and API to make your map interactive. Register and try for free our APIs.