Skip to content

Instantly share code, notes, and snippets.

@rogergcc
Last active August 12, 2020 23:37
Show Gist options
  • Save rogergcc/4ddc8f9871639aafcbb6795cc2e69670 to your computer and use it in GitHub Desktop.
Save rogergcc/4ddc8f9871639aafcbb6795cc2e69670 to your computer and use it in GitHub Desktop.
Show drawn polygon area
<div id="map"></div>
<div class="calculation-box">
<p>Draw a polygon using the draw tools.</p>
<div id="calculated-area"></div>
</div>
mapboxgl.accessToken =
"TOKEN";
var map = new mapboxgl.Map({
container: "map", // container id
style: "mapbox://styles/mapbox/dark-v10", //hosted style 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 src="https://api.mapbox.com/mapbox-gl-js/v1.9.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.0.9/mapbox-gl-draw.js"></script>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.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;
}
<link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
<link href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.0.9/mapbox-gl-draw.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment