Show drawn polygon area

Use mapbox-gl-draw to draw a polygon and Turf.js to calculate its area in square meters.

NPM module setup


npm install --save @maptiler/sdk @mapbox/mapbox-gl-draw @turf/turf
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
import * as turf from '@turf/turf';

config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
    container: 'map', // container id
    style: MapStyle.STREETS,  //hosted style id
    center: [-91.874, 42.76], // starting position
    zoom: 12 // starting zoom
});

const draw = new MapboxDraw({
    displayControlsDefault: false,
    controls: {
        polygon: true,
        trash: true
    }
});
map.addControl(draw);

//fix conytrols style
const drawControls = document.querySelectorAll(".mapboxgl-ctrl-group.mapboxgl-ctrl");
drawControls.forEach((elem) => {
    elem.classList.add('maplibregl-ctrl', 'maplibregl-ctrl-group');
});

map.on('draw.create', updateArea);
map.on('draw.delete', updateArea);
map.on('draw.update', updateArea);

function updateArea(e) {
    const data = draw.getAll();
    const answer = document.getElementById('calculated-area');
    if (data.features.length > 0) {
        const area = turf.area(data);
        // restrict to area to 2 decimal points
        const rounded_area = Math.round(area * 100) / 100;
        answer.innerHTML =
            '<p><strong>' +
            rounded_area +
            '</strong></p><p>square meters</p>';
    } else {
        answer.innerHTML = '';
        if (e.type !== 'draw.delete')
            alert('Use the draw tools to draw a polygon!');
    }
}
Distance measurement on map

Measure distances

Examples

To calculate distances on the map, simply click on different points to create lines that will measure the distances using turf.length.

Geocoding limit results by a drawn area

Geocoding limit results by a drawn area

Examples

Limit geocoding search results to a drawn polygon bounding box.

Add a pattern to a polygon

Add a pattern to a polygon

Examples

Draw polygons using repeating image patterns with fill-pattern.

Was this helpful?