lmotta

Create a layer with fields of near neighbors

Sep 4th, 2011
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Scripts for Postgres/Postgis
  2. --
  3. -- Create a layer with fields of near neighbors from other layer
  4. --  .Layer 'a' = Target
  5. --  .Layer 'b' = Source of neighbors
  6.  
  7.  
  8. -- In select statement  you can choose the fields in both tables 'a' and 'b'
  9. -- This script can use in 'Custon DB Query' plugin for QGIS
  10. select a.id as gid, a.the_geom, b.id as gid_b, ST_Distance(a.the_geom, b.the_geom) as min_dist_a_b
  11. from
  12.  a,b,
  13. (
  14. -- ID of the near neighbors
  15. SELECT m.id as a_id, m.nn[1] as b_id
  16. FROM
  17.  (SELECT a.id, a.the_geom,
  18.      ARRAY(SELECT b.id
  19.                FROM b
  20.         --WHERE ST_DWithin(a.the_geom, b.the_geom, 5000) -- limit of distance
  21.         ORDER BY ST_Distance(a.the_geom, b.the_geom)
  22.         LIMIT 1) As nn
  23.   FROM a  ) m
  24. ) nn
  25. where
  26.  nn.a_id = a.id and nn.b_id = b.id
Advertisement
Add Comment
Please, Sign In to add comment