Search code examples
qgis

Calculate distance between two points in QGIS field calculator


I'm more or less a beginner with QGIS, I've used version QGIS 3.10. I would like to calculate distances (in meters or kilometers) of a number of points to one certain reference point. Is it possible to do this with the QGIS field calculator? The points are geometry points with latitude and longitude in WGS84. The attribute table looks like:

Point_ID Latitude  Longitude   Distance_m
1        46.27789  9.87763     
2        46.27366  9.87701
3        46.27565  9.88045
4        46.27600  9.87822

Point with ID #1 should be the reference point. The linear distance between point #1 to all the other points is my wished result.

I tried several versions like:

distance(geom_to_wkt($geometry ), geom_to_wkt(POINT('POINT_ID'='1')))

or

distance(geom_to_wkt($geometry ), geom_to_wkt(geometry(get_feature_by_id('Point_ID', '1'))))

while the first geometry includes all points listed in the attribute table and the second geometry is the reference point from which distances should be calculated.

but the result is always "NULL".

The distance matrix is not the aim as I get any distance of any point with it. The aim is a sub matrix of the distance matrix...


Solution

  • You are getting null because it can not find the reference point. You need to search by the layer name not the field name.

    First you should project your points, otherwise you will get results in degrees not meters. Then you can calculate the distance:

    distance(($geometry),geometry(get_feature_by_id('Layer Name', 1)))

    Where "Layer Name" is the name of the layer in the Layers panel (a.k.a. table of contents).

    In your question you are using WKT from longitude and latitude, this can be done from projected x and y values (e.g. UTM) like so:

    distance( geom_from_wkt( 'POINT(' || "x_utm" || ' ' || "y_utm" || ')'), geom_from_wkt( 'POINT(' || attribute(get_feature_by_id('Layer Name', 1),'x_utm') || ' '|| attribute(get_feature_by_id('Layer Name', 1),'y_utm') || ')' ) )

    If you need to you can do the transformations like this:
    x(transform(( geom_from_wkt( 'POINT('||"lon"|| ' '|| "lat" || ')' ) ),'epsg:4326','epsg:code for your UTM zone'))

    y(transform(( geom_from_wkt( 'POINT('||"lon"|| ' '|| "lat" || ')' ) ),'epsg:4326','epsg:code for your UTM zone'))

    I have not found a way to get great circle distance in field calculator.