Display thousands of polygons in Leaflet

In this Leaflet JS example, you will learn how to handle thousands of polygons using the leaflet-maptilersdk plugin. Load large amounts of data into Leaflet without affecting the performance of your application.

This example shows how to add a polygon layer with a color ramp symbol that changes the fill color based on the map zoom level, with the help of the polygon layer helper. Download the building’s sample data.

NPM module setup


npm install --save @maptiler/leaflet-maptilersdk leaflet
import { MaptilerLayer, MapStyle } from '@maptiler/leaflet-maptilersdk';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

const map = L.map('map').setView([41.782993,3.030553], 14);
const mtLayer = new MaptilerLayer({
  apiKey: 'YOUR_MAPTILER_API_KEY_HERE',
  style: MapStyle.DATAVIZ.LIGHT, // optional
}).addTo(map);

mtLayer.on("ready", () => {     
  
  // Leverage the MapTiler SDK layer helpers to easily add polyline / point / polygon / heatmap layers
  mtLayer.addPolygon({
    data: 'guixols.geojson',
    fillColor: [
      {zoom: 14, value: "#593895"},
      {zoom: 15, value: "#761FE8"},
      {zoom: 16, value: "#F1175D"},
      {zoom: 17, value: "#FB3A1B"},
      {zoom: 18, value: "#FBC935"},
      {zoom: 19, value: "#FFAA01"},
    ],
    outline: true,   
    outlineWidth: [
      {zoom: 14, value: 0},
      {zoom: 15, value: 1},
      {zoom: 16, value: 2},
      {zoom: 17, value: 3},
      {zoom: 18, value: 4},
      {zoom: 19, value: 5},
    ],
    outlineColor: [
      {zoom: 14, value: "#805CC2"},
      {zoom: 16, value: "#E25041"},
      {zoom: 18, value: "#FFD65F"},
    ],
    outlinePosition: "inside",
  });

});

Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.

Learn more

Check out the Polygon Layer Helper documentation and look at the Polygon Helper examples to see the visualization possibilities.

Display thousands of lines in Leaflet

Display thousands of lines in Leaflet

Examples

Display thousands of lines efficiently in Leaflet using maptilersdk.

How to create a choropleth Map from GeoJSON using Leaflet

Choropleth GeoJSON

Tutorials

Create a styled choropleth map using GeoJSON and Leaflet.

Show Polygon Data from GeoJSON on the Map

GeoJSON Layer

Tutorials

Add GeoJSON polygon overlays to Leaflet JS maps.

Plotting thousands or millions of points in Leaflet

Plotting millions of points in Leaflet

Examples

Display millions of points efficiently in Leaflet using maptilersdk.

Was this helpful?