6

I have 2 .shp layers in my workspace, polyLayer and pointLayer

Using PyQGIS I'd like to be able to get the distance from the point to the nearest boundary of the polygon.

I've done this sort of thing successfully in PostGIS. It seems like it must be a very commonly used query, but I can't find anything on performing such queries on .shp files using PyQGIS.

Does anyone know how this can be achieved?

Ben Mayo
  • 955
  • 1
  • 11
  • 28
  • This question has already been answered several times it seems ... – Snaileater Aug 05 '15 at 11:50
  • Can you provide a link? – Ben Mayo Aug 05 '15 at 11:55
  • Same or "similar" i would say : http://gis.stackexchange.com/questions/59173/how-to-find-the-nearest-line-to-a-point-in-qgis ... u can use it as starting point ... – Snaileater Aug 05 '15 at 12:01
  • Yep, read that, done it. It does indeed return the ID of the nearest line. I'm trying to get the distance...and need someone to show me in baby steps! – Ben Mayo Aug 05 '15 at 13:16
  • 1
    U can use the "distance" function of the QgsGeometry class, it returns the minimum distance between two geometries (u just have to set these two geometries : your point and the nearest feature u found) – Snaileater Aug 05 '15 at 13:32
  • Yep - getting there! Once I nail it down (and if not beaten to it) I'll post my code. – Ben Mayo Aug 05 '15 at 13:50

1 Answers1

8

Everything's easy when you know how... For simplicity I've put the point's coordinates in here.

#define the point
pt = QgsPoint(289749,56754)
pt =  QgsGeometry.fromPoint(pt)

#get the active polygon
layer = qgis.utils.iface.activeLayer()
polygon = layer.getFeatures().next()
geom = polygon.geometry()

#do the business    
distanceToPolygon = QgsGeometry.distance(pt, geom)
print distanceToPolygon
Ben Mayo
  • 955
  • 1
  • 11
  • 28