我通过从各个图层中选择两个要素来创建线条。当我创建一个表格时,会弹出一个表格。在这种形式中,我想显示来自该行的开始和结束特征的数据。 我目前正在做的是将顶点检索为点:
geom = feature.geometry ()
line = geom.asPolyline ()
pointFather = ligne[0]
pointChild = ligne[-1]
然后我得到每个点的坐标:
xf = pointFather.x()
yf = pointFather.y()
然后我查看每个可能的图层以找到具有相同坐标的要素,只是为了检索我刚刚点击的要素!
for layer in layerList:
provider = layer.dataProvider()
iter = provider.getFeatures()
for feature in iter:
geom = feature.geometry().asPoint()
if geom.x() == xf and geom.y() == yf:
直接检索开始和结束功能必须更容易一些,不是吗?
编辑1:
这是我在PCamargo第一次回答后的尝试:
def retrieve_feature_from_xy(geom,point,layerList):
for layer in layerList:
index = QgsSpatialIndex()
iter = layer.getFeatures()
for feat in iter:
index.insertFeature(feat)
ids = index.intersects(geom.boundingBox())
request = QgsFeatureRequest()
request.setFilterFids(ids)
iter = layer.getFeatures(request)
for feat in iter:
geom2 = feat.geometry().asPoint()
if geom2.x() == point.x() and geom2.y() == point.y():
return feat
编辑2:
这是我在PCamargo第二次评论后的尝试:
def retrieve_feature_from_xy2(geom,point,layerList):
allfeatures = {}
indexes=[]
ids=[]
for layer in layerList:
index = QgsSpatialIndex()
iter = layer.getFeatures()
for feat in iter:
index.insertFeature(feat)
allfeatures[feat.id()]=feat
indexes.append(index)
for index in indexes:
intersect_ids = index.intersects(geom.boundingBox())
ids.append(intersect_ids)
for id in ids:
for i in id:
feat=allfeatures[i]
geom2=feat.geometry().asPoint()
if geom2.x() == point.x() and geom2.y() == point.y():
return feat
编辑3
这是我在PCamargo第三次评论后的尝试:
def retrieve_feature_from_xy3(geom,point,layerList):
allfeatures = {}
indexes=[]
ids=[]
indexDict = {}
intersectsIdsDict = {}
for layer in layerList:
index = QgsSpatialIndex()
iter = layer.getFeatures()
for feat in iter:
index.insertFeature(feat)
allfeatures[layer,feat.id()]=feat
indexes.append(index)
indexDict[layer]=index
for layer, index in indexDict.items():
intersectsIds = index.intersects(geom.boundingBox())
intersectsIdsDict[layer]=intersectsIds
for layer, index in intersectsIdsDict.items():
for id in index:
feat = allfeatures[layer,id]
geom2=feat.geometry().asPoint()
if geom2.x() == point.x() and geom2.y() == point.y():
return feat
答案 0 :(得分:1)
克里斯,
你绝对可以改善类似坐标的外观(代码的第三部分)。
不是循环遍历每个层中的所有要素,而是为每个链接创建空间索引(https://docs.qgis.org/2.2/en/docs/pyqgis_developer_cookbook/vector.html#using-spatial-index)并使用nearestNeighbor。
这将是这样的:
#You only need to create these indices once
indexes=[]
for layer in layerlist:
index = QgsSpatialIndex()
for feat in layer:
index.insertFeature(feat)
indexes.append(index)
现在我们有了索引,我们可以使用更快的地理搜索。
geom = feature.geometry ()
for index in indexes:
intersect_ids = index.intersects(geom.boundingBox())
intersect_ids 是较小的候选要素列表,因此您只能将这些要素与您选择的要素进行比较。
你需要更多地组织这个,但这就是想法