Mapbox-gl-draw
Use mapbox-gl-draw to draw the polygon and Turf.js
to calculate the area of the polygon in square meters.
Description
You can use mapbox-gl-draw and Turf.js
with @openmapvn/openmapvn-gl
to draw polygons and calculate the area of polygons.
Usage
To do this on the map you need to add the code snippet below in your HTML file. This code snippet will show the tool on the map in the bottom left corner.
Draw a polygon using the draw tools.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Openmap.vn Demo Map</title>
<meta
property="og:description"
content="Initialize a map in an HTML element with OpenmapVN GL."
/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://unpkg.com/@openmapvn/[email protected]/dist/maplibre-gl.css"
/>
<script src="https://unpkg.com/@openmapvn/[email protected]/dist/maplibre-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
html,
body,
#map {
height: 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;
}
</style>
<script src="https://www.unpkg.com/@mapbox/[email protected]/dist/mapbox-gl-draw.js"></script>
<link
rel="stylesheet"
href="https://www.unpkg.com/@mapbox/[email protected]/dist/mapbox-gl-draw.css"
/>
</head>
<body>
<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">
import * as turf from "https://esm.sh/@turf/[email protected]";
MapboxDraw.constants.classes.CANVAS = "maplibregl-canvas";
MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl";
MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-";
MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group";
MapboxDraw.constants.classes.ATTRIBUTION = "maplibregl-ctrl-attrib";
const map = new maplibregl.Map({
container: "map",
style:
"https://maptiles.openmap.vn/styles/day-v1/style.json?apikey=YOUR_API_KEY",
center: [105.85237, 21.03024],
zoom: 15,
maplibreLogo: true
});
const 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) {
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 roundedArea = Math.round(area * 100) / 100;
answer.innerHTML = ``;
} else {
answer.innerHTML = "";
if (e.type !== "draw.delete")
alert("Use the draw tools to draw a polygon!");
}
}
</script>
</body>
</html>
info
More information about the @openmapvn/openmapvn-gl
library can be found in the Openmap.vn GL JS documentation.