Skip to content

Instantly share code, notes, and snippets.

@tohka
Last active February 2, 2020 13:22
Show Gist options
  • Save tohka/69fbdd263477e76cb10818bf1e182b8e to your computer and use it in GitHub Desktop.
Save tohka/69fbdd263477e76cb10818bf1e182b8e to your computer and use it in GitHub Desktop.
getFeatureAttribute
from qgis.core import *
from qgis.gui import *
"""
使い方:
getFeatureAttribute(対象レイヤID, 空間関係, 取得したい属性名)
例:
getFeatureAttribute('ポリゴンレイヤ_7dff1692_ba18_4bd1_bf46_63785338b050' , 'intersects', 'name')
レイヤIDは対象レイヤのフィールド計算機を開き @layer_id と入力することで確認できます。
空間関係には 'equals', 'disjoint', 'touches', 'contains', 'intersects', 'within', 'crosses', 'overlaps' の
いずれかを指定します。複数指定はできません。
空間関係は当該地物の、対象レイヤの地物に対する関係です。
もし複数の地物にマッチする場合でも、最初にマッチした地物のみの属性値のみを取得します。
"""
@qgsfunction(args='auto', usesgeometry=True, group='Custom')
def getFeatureAttribute(target_layer_id, relationship, attribute, feature, parent):
target_layer = QgsProject.instance().mapLayer(target_layer_id)
if isinstance(target_layer, QgsVectorLayer):
geom = feature.geometry()
if relationship == 'equals':
check_relation = geom.equals
elif relationship == 'disjoint':
check_relation = geom.disjoint
elif relationship == 'touches':
check_relation = geom.touches
elif relationship == 'contains':
check_relation = geom.contains
elif relationship == 'intersects':
check_relation = geom.intersects
elif relationship == 'within':
check_relation = geom.within
elif relationship == 'crosses':
check_relation = geom.crosses
elif relationship == 'overlaps':
check_relation = geom.overlaps
else:
raise ArgumentError
for f in target_layer.getFeatures():
if check_relation(f.geometry()):
try:
return f[attribute]
except:
return None
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment