MapSnippets logo MapSnippets logo

Fill Layers with MapTiler SDK

MapTiler SDK

Fill a polygon area on a MapTiler SDK map by adding a GeoJSON source with map.addSource() and styling it with a fill layer plus a line layer outline.

progress_activity Loading map...
maptilersdk.config.apiKey = 'YOUR_MAPTILER_KEY';
const map = new maptilersdk.Map({
  container: 'map',
  style: maptilersdk.MapStyle.STREETS,
  center: [2.34, 48.86],
  zoom: 13
});
map.on('load', () => {
  map.addSource('area', {
    type: 'geojson',
    data: { type: 'Feature', geometry: { type: 'Polygon',
      coordinates: [[[2.32, 48.87], [2.36, 48.87], [2.36, 48.85], [2.32, 48.85], [2.32, 48.87]]]
    }}
  });
  map.addLayer({
    id: 'area-fill', type: 'fill', source: 'area',
    paint: { 'fill-color': '#9C27B0', 'fill-opacity': 0.4 }
  });
  map.addLayer({
    id: 'area-outline', type: 'line', source: 'area',
    paint: { 'line-color': '#9C27B0', 'line-width': 2 }
  });
});

How to draw a filled polygon with MapTiler SDK

Add a GeoJSON source with a Polygon geometry and render it with a fill layer. A separate line layer draws the border, since fill layers do not render outlines by default.

Polygon coordinates must form a closed ring, with identical first and last coordinates. The outer ring uses counterclockwise winding, and holes use clockwise winding.

The fill-opacity at 0.4 makes the polygon translucent so the basemap remains visible underneath.

Key APIs

API Description Docs
fill layer type Render filled polygons docs.maptiler.com/sdk-js/api/
fill-color Paint property for fill color docs.maptiler.com/sdk-js/api/
fill-opacity Paint property for transparency docs.maptiler.com/sdk-js/api/

FAQ

How do I add a hole in the polygon?

Add a second ring to the coordinates array. The first ring is the outer boundary, and subsequent rings are holes.

Can I make the polygon clickable?

Yes. Use map.on('click', 'area-fill', (e) => { ... }) to handle clicks on the polygon layer.

Common mistakes

  • Not closing the polygon ring. The first and last coordinate must match
  • Using only a fill layer and expecting a visible border. Add a separate line layer for the outline
  • Nesting coordinates incorrectly. Polygon coordinates are [[[lng, lat], ...]] (an array of rings)

Build maps using MapTiler SDK with AI

Generate code like this fill layers with maptiler sdk example using the MapTiler SDK skill in your IDE.