# Calculating the shortest distance between polygons in QGIS

In QGIS 3.12 I need to calculate the shortest distance from the boundary of one polygon to the boundary lines of a set of polygons as shown in the image below

I have followed the instructions according to this question Calculating shortest distance between multiple Polygon borders to a common Polygon border?.

It seemed to provide a good solution using the field calculator to generate a new feature in the attribute table (eg the attribute table of the blue polygons) using the following formula

``````distance(\$geometry, geom_from_wkt('Polygon ((........))'))
``````

as described in the above link. However, when I randomly checked some of the distances using the measuring tool, while many of my tests were consistent, I found several that were incorrect e.g 196.11 km vs 216.9 km.

All the shapefiles and my project are in the same projection system.

I cannot figure out why there are the errors or if this is the best way to calculate these distances.

Ideally I would like tracklines generated to show the shortest distance, however this may be over complicated.

• Have you had a look at `join by nearest`? If so, what does it lack?
– Erik
Sep 25, 2020 at 11:08

If only length values are needed, please use the following expression in the "Field Calculator"

``````length(
shortest_line(
\$geometry,
geometry(get_feature('building', 'osm_id', '1234567'))
)
)
``````

In my example I am referring to a feature by its `"id"` from a certain layer, otherwise use `geom_from_wkt()`.

If new geometries have to be created, then try using the "Geometry by expression" geoalgorithm from the QGIS's Toolbox with the following expression:

``````shortest_line(
\$geometry,
geometry(get_feature('building', 'osm_id', '1234567'))
)
``````

• Thank you so much this looks wxactly what I am trying to do Sep 25, 2020 at 15:22