PyQGIS 스크립트 업데이트
Oct 23 2020
이 링크에서 https://sisteme-ig.com/questions/10129/creacion-automatizada-de-lineas-perpendiculares-entre-una-ca#232721 @Xunilk가 스크립트를 공유했습니다.
mapcanvas = iface.mapCanvas()
layers = mapcanvas.layers()
p_lyr = layers[0]
l_lyr = layers[1]
epsg = p_lyr.crs().postgisSrid()
uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&field=distance:double(20,2)&index=yes"
dist = QgsVectorLayer(uri,
'dist',
'memory')
QgsMapLayerRegistry.instance().addMapLayer(dist)
prov = dist.dataProvider()
lines_features = [ line_feature for line_feature in l_lyr.getFeatures() ]
points_features = [ point_feature for point_feature in p_lyr.getFeatures() ]
feats = []
for p in points_features:
minDistPoint = min([l.geometry().closestSegmentWithContext( p.geometry().asPoint() ) for l in lines_features])[1]
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPolyline([p.geometry().asPoint(), minDistPoint]))
feat.setAttributes([points_features.index(p),feat.geometry().length()])
feats.append(feat)
prov.addFeatures(feats)
그러나 그 QGIS에서 다음 오류가 발생합니다.
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.12\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 5, in <module>
TypeError: index 0 has type 'QgsPointXY' but 'QgsPoint' is expected
이 오류가 발생하지 않도록이 Python 코드를 어떻게 변경할 수 있습니까?
답변
3 KadirŞahbaz Oct 23 2020 at 18:18
변경 QgsMapLayerRegistry에 QgsProject와 fromPolyline에 fromPolylineXY.
fromPolyline예상 QgsPoint하지만 asPoint메서드는 QgsPointXY인스턴스를 반환 합니다.
다음과 같이 사용하십시오.
layers = iface.mapCanvas().layers()
p_lyr = layers[0]
l_lyr = layers[1]
epsg = p_lyr.crs().postgisSrid()
uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&field=distance:double(20,2)&index=yes"
dist = QgsVectorLayer(uri, 'dist', 'memory')
prov = dist.dataProvider()
lines_features = [ line_feature for line_feature in l_lyr.getFeatures() ]
points_features = [ point_feature for point_feature in p_lyr.getFeatures() ]
feats = []
for p in points_features:
minDistPoint = min([l.geometry().closestSegmentWithContext( p.geometry().asPoint() ) for l in lines_features])[1]
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPolylineXY([p.geometry().asPoint(), minDistPoint]))
feat.setAttributes([points_features.index(p),feat.geometry().length()])
feats.append(feat)
prov.addFeatures(feats)
QgsProject.instance().addMapLayer(dist)
1 BERA Oct 23 2020 at 17:35
QgsGeometry.fromPolyline 의 목록을 원하시면 QGSPoints의을 (를) 전달하고 있습니다 QGSPointXY. 다음으로 변환QGSPoints(thexypoint)
따라서 줄을 변경하십시오.
feat.setGeometry(QgsGeometry.fromPolyline([p.geometry().asPoint(), minDistPoint]))
에:
feat.setGeometry(QgsGeometry.fromPolyline([QgsPoint(p.geometry().asPoint()), QgsPoint(minDistPoint)]))