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?

6
  • This question has already been answered several times it seems ...
    – Snaileater
    Commented Aug 5, 2015 at 11:50
  • Can you provide a link?
    – Ben Mayo
    Commented Aug 5, 2015 at 11:55
  • Same or "similar" i would say : gis.stackexchange.com/questions/59173/… ... u can use it as starting point ...
    – Snaileater
    Commented Aug 5, 2015 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
    Commented Aug 5, 2015 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
    Commented Aug 5, 2015 at 13:32

1 Answer 1

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
1
  • 3
    "Everything's easy when you know how" - Such a true statement! +1.
    – Joseph
    Commented Aug 5, 2015 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.