Skip to content

fix(polygonize): deduplicate segments in planar graph#3045

Open
Traksewt wants to merge 2 commits intoTurfjs:masterfrom
agriwebb:fix/polygonize-duplicate-segment
Open

fix(polygonize): deduplicate segments in planar graph#3045
Traksewt wants to merge 2 commits intoTurfjs:masterfrom
agriwebb:fix/polygonize-duplicate-segment

Conversation

@Traksewt
Copy link
Copy Markdown

@Traksewt Traksewt commented Mar 31, 2026

  • Meaningful title, including the name of the package being modified.
  • Summary of the changes.
  • Heads up if this is a breaking change.
  • Any issues this resolves.
  • Inclusion of your details in the contributors field of package.json - you've earned it!
  • Confirmation you've read the steps for preparing a pull request.

Summary

When input geometry contains duplicate line segments (the same segment appearing more than once), @turf/polygonize silently returns 0 polygons instead of the expected result.

Bug

// A simple square with one duplicated segment — should produce 1 polygon
const lines = featureCollection([
  lineString([[0, 0], [1, 0]]),
  lineString([[1, 0], [1, 1]]),
  lineString([[1, 1], [0, 1]]),
  lineString([[0, 1], [0, 0]]),
  lineString([[0, 0], [1, 0]]),  // duplicate of first segment
]);

polygonize(lines); // => 0 polygons (expected 1)

Root cause

Graph.addEdge() creates a new pair of directed edges for every input segment, including duplicates. The duplicate edges corrupt the planar graph topology, causing edge-ring traversal to fail.

Fix

Track seen edge IDs in Graph and skip segments that have already been added. Two lines in addEdge() plus cleanup in removeEdge().

Test

Added a regression test with the above scenario — confirms polygonize correctly returns 1 polygon when a duplicate segment is present.

This is not a breaking change. Inputs that previously worked continue to produce the same output. Only the failure case (duplicate segments -> 0 polygons) is fixed.

Relates to #1714.


Note: This is a focused subset of #1714, which was opened in 2019 but covered multiple fixes in a single large PR (1000+ lines). This PR intentionally targets just the duplicate segment issue to keep the change small and reviewable per the contributing guidelines. Happy to follow up with separate PRs for the other polygonize issues if this lands.

@Traksewt
Copy link
Copy Markdown
Author

Traksewt commented Apr 2, 2026

Hi @NickCis and @DenisCarriere, I have a few fixes to make this more robust, I can do them 1 at a time. Let me know if it is of interest and if there is anything else you need. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant