Smooth polygon animations using turf.js
In a recent mapping project I included subtle animation to help highlight different areas. As the map flies around to each bounding box, the boxes (polygons) themselves become visible and their boundaries are drawn. After automating this functionality to a certain extent, I thought it would be nice to share how it was done. To see all of the code in one place please visit this Github repo.
To summarize, animating any polygon/polyline in Mapbox can be done by measuring the total length of a polygon boundary
turf.lineDistance(), calculating equidistant points along the boundary
turf.along(), and then updating the animated map layer with
Previously I had used functions in QGIS like ‘Points along geometry’ to calculate evenly spaced points along a line for a smooth animation. The obvious drawback was that each polygon I wanted to animate would need to be analyzed in QGIS first. Turf allows you to generate the ‘Points along geometry’ dynamically – meaning it can calculate a smooth animation path for any series of coordinates.
For fun, I wanted to show this functionality on something not traditionally thought of as a map to show that turf can handle almost any shape. I thought a ‘connect the dots’ worksheet would be perfect.
I’ve placed comments in the code to help explain how it fully works so please look at the example code here. Hoping these examples can help someone add animation to their Mapbox maps. If you have any questions please reach out on Twitter.
Also, here are a couple of articles that helped me: