TransWikia.com

Convert geometry to feature with QGIS expressions

Geographic Information Systems Asked on June 30, 2021

With QGIS expressions, if I have a feature, I can get the corresponding geometry with geometry (feature). How is it possible the other way round: if I have a geometry to get the feature (or feature id) of this geometry? Unfortunately, an expression like feature (geometry) does not exist. This could be useful to access attributes of this geometry.

If a feature consists of three parts: 1) feature-id, 2) attributes and 3) geometry, than you have expressions to get the corresponding feature for the first two of these three inputs: 1) get_feature_by_id(layer,feature_id)
, 2) get_feature(layer,attribute,value). There is missing something like get_feature_by_geometry (geometry).


Just to illustrate a use case (the question is not about this example: it should just help to understand what this could be used for). I have a point- and a line layer, both in red on the screenshot. To each point, I want to assign the id (or any other attribute) of the nearest line.

I can easily get the geometry of the nearest line: the black dotted copy of the original red line, created with geometry generator on the point layer: array_first ( overlay_nearest ( 'line', $geometry ) ). To access the attributes of the line, there is the function attribute ( feature , attribute_name ) . But I first should be able to get the feature-id of the geometry to be able to paste it as first arguement.

QGIS does not accept to input a geometry for the feature part of the expression, I get an Evaluation error: Cannot convert to feature.

enter image description here

One Answer

You can access the feature-id by using $id instead of $geometry and then use get_feature_by_id() to turn this feature-id integer value into an actual feature of a layer. This can then be used to get the attribute() or attributes(). As a whole:

attribute(get_feature_by_id('line',array_first(overlay_nearest('line',$id))),'fieldname')

You can also skip the get_feature_by_id() part by using $currentfeature instead of $id:

attribute(array_first(overlay_nearest('line',$currentfeature)),'fieldname')

Correct answer by MrXsquared on June 30, 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