TransWikia.com

QGIS: How to get distance from a feature in another layer

Geographic Information Systems Asked by Keith Snyder on March 17, 2021

I currently have a layer with milepost locations on a railroad track. I’m creating another layer while driving down the tracks where I need to add comments. There’s a field in the comments layer for milepost location and I’d like it to be accurate to two decimals. When digitizing my comments, I’d like it to automatically give me the milepost location. It doesn’t have to be exact, if it could just find the two nearest mileposts, determine which of those two was the smaller number, then give me the distance from that milepost added to the milepost number. I’m trying to figure out how to make an expression for a default value that will fill in this field while digitizing, but I can’t figure out where in the expressions list you can find a distance from a point in another layer.

EXAMPLE:

I’m driving down the tracks and I’m currently .6 miles from milepost 8 and .4 miles from milepost 9. When I "Add Point", I’d like the Milepost field to default to a value of "8.60."

One Answer

You may try the following expression. It loops other features from 'your_joined_layer_identifier', order by distance between the current geometry to each 'your_joined_layer_identifier' feature geometry to get milepost_id from nearest to furthest. Then, we get only the nearest with array_get and cast it to real to make calculation. We loop again to get the minimum distance to the nearest milepost and we sum both. We apply rounding to get two decimals.

round(
  to_real(
    array_get(
      aggregate(
        layer:= 'your_joined_layer_identifier',
        aggregate:='array_agg',
        expression:="your_col_with_milepost_id",
        order_by:=distance($geometry,geometry(@parent))
      ),
      0
     )
  )
  +
  aggregate(
    layer:= 'your_joined_layer_identifier',
    aggregate:='min',
    expression:=distance($geometry,geometry(@parent))
  ),
  2
)

The main drawback is that it will work nicely between points layer to points layers but measuring a distance between a line with multiple sections and a point is not so simple. It's needed to find the nearest line section from your point, project a point on the section to get the point location and then measure the distance between projected point and your point. In worst case, it should help get started using distance between a layer geometry and the geometries of another layer.

Correct answer by ThomasG77 on March 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP