UNL Map JSUNL Map JS DocsExamplesShow drawn polygon area

Show drawn polygon area

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

Note
If you want to test this example, edit it in JSFiddle or CodePen and replace the "YOUR-OWN-API-KEY" and "YOUR-OWN-VPM-ID" placeholders with your actual api key and vpm id.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Show drawn polygon area</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://unpkg.com/unl-map-js@0.1.5/lib/unl-map-js.js"></script>
<link href="https://unpkg.com/unl-map-js@0.1.5/lib/unl-map-js.css" rel="stylesheet" />
<link
href="https://unpkg.com/maplibre-gl@2.1.9/dist/maplibre-gl.css"
rel="stylesheet"
/>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</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>
<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/plugins/mapbox-gl-draw/v1.2.0/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>
var map = new UnlSdk.Map({
container: "map", // container id
apiKey: "YOUR-OWN-API-KEY",
vpmId: "YOUR-OWN-VPM-ID",
center: [-91.874, 42.76], // starting position
zoom: 12, // starting zoom
});
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true,
},
});
map.addControl(draw);
map.on("draw.create", updateArea);
map.on("draw.delete", updateArea);
map.on("draw.update", updateArea);
function updateArea(e) {
var data = draw.getAll();
var answer = document.getElementById("calculated-area");
if (data.features.length > 0) {
var area = turf.area(data);
// restrict to area to 2 decimal points
var 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!");
}
}
</script>
</body>
</html>