Skip to content

Instantly share code, notes, and snippets.

@sfkeller
Created September 14, 2016 14:15
Show Gist options
  • Save sfkeller/9ba89b2a43be432c92b6335777ce6db9 to your computer and use it in GitHub Desktop.
Save sfkeller/9ba89b2a43be432c92b6335777ce6db9 to your computer and use it in GitHub Desktop.
Snapping a polygon (= (to-)snappoly) to a reference polygon (refpoly)
/*
Snapping a polygon (= (to-)snappoly) to a reference polygon (refpoly).
Note that snapping only works on nearby points of two polygons.
So there are maybe orphaned points on snappoly which still are nearby
a refpoly segment but did not snap in the first round. So, in addition
the closest points on refpoly to the orphaned snappoly points are
collected and the first snapped poly output is snapped again given
this closest points collection.
*/
with
refpoly(gid, geom) as (
select 1, ST_GeomFromText('POLYGON ((4 1, 4 8, 2 7, 2 3, 4 1))')
),
snappoly(gid, geom) as (
select 11, ST_GeomFromText('POLYGON ((6 2, 6 4, 6 6, 7 8, 9 8, 9 3, 6 2))')
),
snappedpoly(gid, geom) as (
select
snappoly.gid+100 as gid,
ST_Snap(snappoly.geom, refpoly.geom, 2.5) as geom
from
snappoly,
refpoly
)
select
c.gid,
ST_AsText(ST_Snap(c.geom, d.geom, 2.5)) as snapped_geom_fixed,
ST_AsText(c.geom) as snapped_geom
from
snappedpoly c,
(select
ST_Collect(geom) as geom
from (
select
ST_ClosestPoint(a.geom, b.geom) as geom
from
refpoly a,
(select (ST_DumpPoints(geom)).geom as geom from snappedpoly) b
where ST_Distance(b.geom, a.geom)>0 and ST_Distance(b.geom, a.geom)<2.5 ) tmp
) d;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment