I am using the below code to add a custom control to draw the polygon on the map and show the area on the side(on a div) of the screen.
change() {
this.map.on('load', () => {
this.draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});
this.map.addControl(this.draw);
this.map.on('draw.create', (e) => {
this.updateArea(e)
});
this.map.on('draw.delete', (e) => {
this.updateArea(e)
});
this.map.on('draw.update', (e) => {
this.updateArea(e)
});
}
}
}
updateArea(e) {
const data = this.draw.getAll();
if (data.features.length > 0) {
const area = turf.area(data);
const rounded_area = Math.round(area * 100) / 100;
this.selectedArea = rounded_area + ' sq m';
} else {
if (e.type === 'draw.delete') {
this.selectedArea = '0 sq m';
this.perimeter = '0 m';
}
}
console.log(this.map.getStyle())
}
I want to display the area on the hover of the drawn polygon. And, I can also draw multiple polygons, so I need to show the popup with the area whenever I hover over the drawn polygon.
What I am not able to understand is, in which specific layer/source are these polygons drawn? I went over the 'mapbox-gl-draw' documentation,but there is no mention about the layer. I just found that when I console this.map.getStyle()
as can be seen above, I get below object:
{
center: (2)[0, 0],
glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
layers: (151)[{
…}, ...],
metadata: {
mapbox: type: "default",
mapbox: origin: "streets-v11",
mapbox: autocomposite: true,
mapbox: groups: {
…}
},
name: "Mapbox Streets",
sources: {
composite: {
…},
contour: {
…},
geojson: {
…},
orthomosaic: {
…},
dsm: {
…},
…
},
sprite: "mapbox://sprites/mapbox/streets-v11",
version: 8,
zoom: 3,
}
So, I see in the browser console that sources in this above object contain the mapbox-gl-draw-hot
and mapbox-gl-draw-cold
sources. And they contain the active and stale drawn polygons(and their corresponding feature data), but how do I use that data to enable popups on the map that will show me the corresponding area on hovering. I tried playing around with the id of the generated polygon in these sources, but with no luck.
Any suggestions welcome.