6

I'd like to open a popup in on the midpoint of a polyline/linestring in Mapbox GL, like it's the default case in Leaflet.

How can I do this via turf.js? If I use centroid/center/centerOfMass it will get a point usually not on the line, but somewhere next to it.

My only idea is to:

  1. Measure the lenght of the line in some units
  2. Use along() with the half of the measured distance.

Is this really the best option?

2
  • 1
    That sounds like the best option to me. Commented May 14, 2018 at 3:52
  • I've tried the midpoint() function from Turf, but the point was not along the line. Then I came across this answer, and tried the approach of first calculating the line length and then moving half the length on the line. It worked for me Commented Jan 23, 2023 at 10:58

1 Answer 1

0

I have same issue, see my screenenter image description here

I fixed it by use the post author's idea, successfully place the center point along the line. This is my code to fix the issue. enter image description here

This is fixed result, compare it with top screen (unfixed issue)

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.