Created
May 15, 2024 20:35
-
-
Save stavros-k/ca179e150af84f011dfcd84df706cad4 to your computer and use it in GitHub Desktop.
Single polyline to multiple paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// iOS have a limitation of 512 points / 256 coordinates pairs. | |
// Paths "d" property must have the previous 2 points at the start | |
// so we don't have gaps in the path. | |
// Never use more than 512 points in a path | |
// The lower we go the more "accurate" will be the draw time | |
// on all paths. the higher the number of points, we risk | |
// having the last part go too slow. | |
const maxPointsPerPath = 100; | |
export const polyLineToPaths = (points: string) => { | |
let paths: Array<string> = []; | |
const data = points.replaceAll(",", " ").split(" "); | |
if (data.length % 2 !== 0) { | |
throw new Error( | |
"Polyline [points] must have an even number of coordinates/points" | |
); | |
} | |
const PREVIOUS_POINTS = 2; | |
// Split the points into chunks of 256 points | |
for (let i = 0; i < data.length; i += maxPointsPerPath) { | |
// If we have reached the end of the points, get the last 2 | |
// from the previous chunk and the remaining points | |
if (i + maxPointsPerPath > data.length) { | |
const remainingPoints = data.slice(i - PREVIOUS_POINTS); | |
paths.push(remainingPoints.join(" ")); | |
break; | |
} | |
if (paths.length === 0) { | |
// If this is the first chunk, just add it to the paths | |
const chunk = data.slice(i, i + maxPointsPerPath); | |
paths.push(chunk.join(" ")); | |
} else { | |
// This is a "middle" chunk, so we start from the last 2 points of | |
// the previous chunk and add the remaining points | |
const chunk = data.slice(i - PREVIOUS_POINTS, i + maxPointsPerPath); | |
paths.push(chunk.join(" ")); | |
} | |
} | |
return paths; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment