Julia Andersson
Julia Andersson

Reputation: 21

Show length of polygon in Mapbox GL JS draw

I'm new to coding in javascript etc. My backround is a little knowlegde in Python.

I'm following this example https://docs.mapbox.com/mapbox-gl-js/example/mapbox-gl-draw/ of how to draw a polygon in Mapbox and then showing the area of the polygon(s).

What I want also to do is to show the length of each drawn side of the polygon and be able to show it for the user and not only the area.

It would be extra-great if a label of the length could be shown next to each side of the polygon in the map. Any tips of how to do this? I would be really grateful, thanks!

Upvotes: 1

Views: 1208

Answers (1)

D.matoschaves
D.matoschaves

Reputation: 36

I'd suggest you use the library turf, which has really useful helper methods for this kind of geographic manipulation, and coincidentally (or not), the example you mention also uses it to calculate the area.

So what you'll need to do is to extract the 4 or more points that form the polygon once it is drawn from data (which will have the form of a geojson polygon). Then, with those points as input and using the helper length you can retrieve the lengths of each side of the polygon.

If then you'd like to show those lengths above the mid point of each respective line of the polygon, you could use the helper midpoint to get the coordinates on which you could create a marker with that information. To create markers you can check this example (although in your case you'd probably want to set the flag draggeable to false).

Hope this helps :)

Upvotes: 2

Related Questions