Show drawn polygon area
Use mapbox-gl-draw to draw a polygon and Turf.js to calculate its area in square meters.
See the example: https://docs.mapbox.com//mapbox-gl-js/example/mapbox-gl-draw/
by Nikolay Petrov
January 06, 2021
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css">
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.css">
<div id="map"></div>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoicGV0cm92bm4iLCJhIjoiVHJkcXROMCJ9.hzniKblVA-O0YJSvCfwztg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
center: [28.86802, 57.76297],
zoom: 15
});
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});
map.on('load', function () {
map.addControl(draw);
map.addSource('places', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
"id":4,
"type":"Feature",
"properties":{
"description":"большой полигон (4 точки)",
"state":0
},
"geometry":{
"type":"Polygon",
"coordinates":[[[28.608784675598145,57.78687316908008],[28.747360872381563,57.800526391777424],[28.719108974599408,57.65387530519655],[28.608784675598145,57.78687316908008]]]
}
},
{
"id":21,
"type":"Feature",
"properties":{
"description":"Маленький полигон (много точек)",
"state":0
},
"geometry":{
"type":"Polygon",
...