MapSnippets logoMapSnippets logo

Fill Layers with MapTiler SDK

MapTiler SDK

Draw a filled polygon on the map using a GeoJSON source and a fill layer with MapTiler SDK.

progress_activityLoading 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 it works

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: the first and last coordinate must be identical. The outer ring uses counterclockwise winding, holes use clockwise.

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, 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], ...]] (array of rings)
auto_awesome

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.