I have the following situation:

enter image description here

Some points are outside the polygons and some are in. I want a new field in my point layer with the closest distance to its closest polygon. The points inside a polygon should have the value zero and outside the polygon it should be the distance to the next segment of the polygon. Not the center or the node.

I have tried the "distance to nearest hub" tool, but it gives me the distance to the center of the neighbor polygon.

I have tried the GRASS command "v.distance" but this only makes a join between the two Layers. "v.distance" seems to be the GRASS tool for "QGIS JoinAttributeByNearest". There is no "distance" field in the Attribute table of the new layer.

Same with "JoinAttribteByNearest"... it doesn't give me the distance either.

The Pluging "NNJOIN" works perfectly well for what I need but I want to do this as part of a standalone PyQGIS script and to include "NNJOIN" in it is kind of complicated, thus I'm hoping to find a different solution.

Perhabs PostGIS can help me out here, but do I need to install PostGIS first to use its functionality? And if yes, do the People I'm writing this script for also need to install PostGIS to use my script?

Any other ideas what I could do to get the closest distance from the points to the polygons?

I'm using QGIS3.4

1 Answer 1


I would do this in a three step workflow:

  1. Perform a Join attributes by nearest (It definitely yields a distance column - although calculation is purely cartesian). The distance will be measured between points and the segments of the polygon as the algorithm uses QgsGeometry::nearestPoint() in the backend implementation.
  2. Perform the Select by Location on your result point set from step one with the polygons, selecting those points that are contained in the polygon.
  3. Use use the field calculator with the distance field from step one to set the selected features distance (those contained by the polygons) to zero.

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.