Fix: Handle sf objects with Z/M dimensions in leaflet rendering #962
+104
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
Leaflet fails to render simple features (sf objects) with Z (elevation) or M (measure) dimensions, throwing obscure errors instead. This affects LINESTRING, POINT, POLYGON, and other geometry types when they contain 3D or 4D coordinate data.
Root Cause
The internal
sf_coords()
function expects exactly 2D coordinates (lng, lat) but sf objects with:When
sf_coords()
tries to assign 2 names to 3+ columns, it fails with an error.Solution
Following @jcheng5's suggestion, this PR adds
sf::st_zm()
calls to remove Z and M dimensions at all entry points where sf objects are processed. Thest_zm()
function:Changes
Added
sf::st_zm()
calls to 5 methods inR/normalize-sf.R
:sanitize_sf()
- handles sf data framespointData.sfc_POINT()
- handles sfc_POINT collectionspointData.POINT()
- handles individual POINT objectspolygonData.sfc()
- handles sfc collections (LINESTRING, POLYGON, etc.)polygonData.sfg()
- handles individual geometry objectsThis ensures ZM dimensions are removed regardless of how sf objects enter the leaflet system.
Testing
Added comprehensive test coverage for:
All tests verify that geometries with Z/M dimensions are correctly converted to 2D coordinates and render without errors.
Example
After this fix, the following code works correctly:
Fixes issue where sf objects with Z or ZM dimensions fail to map.
Original prompt
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.