here is the function of drawing polygon in leaflet map.
onDrawCreated(e: any) {
const { layerType, layer } = e;
if (layerType === "polygon") {
const polygonCoordinates = layer._latlngs;
console.log(polygonCoordinates);
}
this.drawnItems.addLayer(e.layer);
}
And here the polygonCoordinates;
Array(1)
0
:
Array(4)
0
:
LatLng {lat: 54.23955053156179, lng: -112.10449218750001}
1
:
LatLng {lat: 50.064191736659104, lng: -108.4130859375}
2
:
LatLng {lat: 48.19538740833338, lng: -116.80664062500001}
3
:
LatLng {lat: 52.07950600379697, lng: -115.66406250000001}
length
:
4
[[Prototype]]
:
Array(0)
length
:
1
[[Prototype]]
:
Array(0)
How can I show this coordinates on function with popup?
Thank you in advance for your help!
There are many ways to do that. One way is to build an array that will contain all the lat lngs
and then join them inside the popup in order to visualize them. Then using polygon's bindPopup
and openPopup
methods you can display them.
onDrawCreated(e: any) {
const { layerType, layer } = e;
if (layerType === "polygon") {
const polygonCoordinates = layer._latlngs;
console.log(polygonCoordinates);
const allCoordsInOneArray = [];
polygonCoordinates[0].forEach((item) => {
allCoordsInOneArray.push(item.lat.toFixed(2));
allCoordsInOneArray.push(item.lng.toFixed(2));
});
console.log(allCoordsInOneArray);
layer
.bindPopup(`Polygon coordinates are ${allCoordsInOneArray.join(", ")}`)
.openPopup();
}
this.drawnItems.addLayer(e.layer);
}
Normally the popup should auto trigger once you form the polygon. If it does not simply click the polygon and you will get it open.