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!');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Show drawn polygon area | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<style>
.calculation-box {
height: 75px;
width: 150px;
position: absolute;
bottom: 40px;
left: 10px;
background-color: rgba(255, 255, 255, 0.9);
padding: 15px;
text-align: center;
}
p {
font-family: 'Open Sans';
margin: 0;
font-size: 13px;
}
</style>
<link
rel="stylesheet"
href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.2/mapbox-gl-draw.css"
type="text/css"
/>
<div id="map"></div>
<div class="calculation-box">
<p>Draw a polygon using the draw tools.</p>
<div id="calculated-area"></div>
</div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}
Related examples
Measure distances
ExamplesTo 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
ExamplesLimit geocoding search results to a drawn polygon bounding box.