Saya memberikan contoh penyelesaian tugas yang sama dengan aplikasi mandiri pyqgis (3.2). Di bawah kode python
from qgis.core import QgsPointXY, QgsApplication, QgsVectorLayer, QgsFeature, QgsGeometry
from PyQt5.QtWidgets import QApplication
import sys
import math
def main():
print('Start program')
qgis_prefix_path = 'C:\\OSGeo4W64\\apps\\qgis'
app = QApplication(sys.argv)
QgsApplication.setPrefixPath(qgis_prefix_path, True)
QgsApplication.initQgis()
point_path = 'd:/Users/Bogomolov/Qgis/Test_prj/point.shp'
line_path = 'd:/Users/Bogomolov/Qgis/Test_prj/lines.shp'
point_layer = QgsVectorLayer(point_path, "pointlayer", "ogr")
layer = QgsVectorLayer(line_path, "linelayer", "ogr")
for feature in point_layer.getFeatures():
geom: QgsGeometry = feature.geometry()
pnt: QgsPointXY = geom.asPoint()
length = feature['distance']
bearing = feature['bearing']
id = feature['id']
print('id=', id)
pnt0 = direct_geodetic_task(pnt, length / 2, bearing + 180)
pnt1 = direct_geodetic_task(pnt, length / 2, bearing)
points = []
points.append(pnt0)
points.append(pnt1)
fields = layer.dataProvider().fields()
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPolylineXY(points))
feature.setFields(fields)
feature.setAttribute('id', id)
layer.dataProvider().addFeature(feature)
# layer.commitChanges()
QgsApplication.exitQgis()
def direct_geodetic_task(pnt, dist, bear):
if bear > 360.0:
bear = bear - 360
if bear < 0:
bear = 360 + bear
deg = bear * math.pi / 180
dx = dist * math.sin(deg)
dy = dist * math.cos(deg)
x = pnt.x() + dx
y = pnt.y() + dy
return QgsPointXY(x, y)
if __name__ == '__main__':
main()
Hasilnya sama