d3 / d3-geo-polygon

Clipping and geometric operations for spherical polygons.
https://d3.observablehq.cloud/d3-geo-polygon/
Other
113 stars 23 forks source link

Can this library be used with other projections? #15

Closed DenMesh closed 6 years ago

DenMesh commented 6 years ago

Namely, d3.geoAlbers? I am trying to use preclipping and am getting very strange results.

More to the point. Polygon 1: [ [ [ 30, 60 ], [ 90, 60 ], [ 90, 30 ], [ 30, 30 ], [ 30, 60 ] ] ] Polygon 2: [ [ [ 45, 75 ], [ 75, 75 ], [ 75, 15 ], [ 45, 15 ], [ 45, 75 ] ] ]

Projection: d3.geoAlbers() .rotate([-105, 0]) .center([-10, 65]) .parallels([52, 64]);

Below is a picture made in qGis, cyan polygon (P2) is being clipped, green is the one doing the clipping (P1) (the one passed to geoClipPolygon and the result passed to preclip). Both polygons are already projected (but not preclipped). intersection

After projecting, P2 is null.

Fil commented 6 years ago

I believe the null result is because preclipping works on spherical coordinates before rotation is applied.

In other words P1 would be projected with rotate([0,0]) and P2 with rotate([-105,0]),

If you set the projection.rotate to [0,0] the two polygons overlap as expected: https://beta.observablehq.com/@fil/clipping-albers

To account for the rotation, you might be able to apply d3.geoRotation([-105,0]).invert on P1 when you define the preclip. Let me know how it goes!

Also, to compute polygon intersections in 2D (projected) you might want to test https://www.npmjs.com/package/martinez-polygon-clipping or https://www.npmjs.com/package/turf-clip

DenMesh commented 6 years ago

Could you elaborate on the "geoRotation" bit? I don't quite get where to apply it.

With regards to 2D clipping, those two libraries are the reason I am trying to use this one. I have a highly "kinked" (as defined in turf) polygon that totally breaks both of them. There is a workaround, but if I can get this library to work, it may arguably be faster.

Fil commented 6 years ago

Yes, I've put up the code for the rotation at https://beta.observablehq.com/@fil/clipping-albers#preclip

I'd be curious to see the polygons you're working with :)

DenMesh commented 6 years ago

Yes, thank you, this works perfectly. As for the files, see attached archive. r.json is the clippee, p.json is the clipper. r.json is the kinked one, btw, I ended up switching them around. They are, respectively, borders of a Russian administrative subdivision and growing area of some plant species.

Also, if you switch the clepper and the clippee ( r as clipper, p as clippee), you get weird polygon errors where it seems to confuse the edges some vertices belong to. It is not a pressing issue, as a simple reversal of roles fixes it, but may be some thing you may wish to investigate.

geometry.zip