3

In my QGIS3 Plug-in I have this code to draw a line between two points. The code works, but after running it, QGIS zooms somewhere in the middle of Pacific Ocean, when I'd like to zoom on the new layer ("line"). The problem occurs at the last line of this code when I call addMapLayers().

def drawLine(self, line_start, line_end):
  start_point = QgsPoint(line_start.asPoint())
  end_point = QgsPoint(line_end.asPoint())        
  v_layer = QgsVectorLayer("LineString", "line", "memory")
  pr = v_layer.dataProvider()
  seg = QgsFeature()
  seg.setGeometry(QgsGeometry.fromPolyline([start_point, end_point]))
  pr.addFeatures( [ seg ] )
  v_layer.updateExtents()
  crs = v_layer.crs()
  crs.createFromId(4326)
  v_layer.setCrs(crs)
  QgsProject.instance().addMapLayers([v_layer])

I tried to add iface.zoomToActiveLayer() but nothing changed. How can I zoom on this new layer avoiding the Pacific Ocean issue?

3

Try specifying the CRS when you construct your QgsVectorLayer object e.g.

v_layer = QgsVectorLayer('LineString?crs=epsg:4326', 'line', 'memory')

Unfortunately, you don't show us what objects you are passing to your drawLine() function as the line_start and line_end arguments, however running the code below which directly creates QgsPoint() objects for the start_point and end_point works fine in the Python console in QGIS 3.4.

start_point = QgsPoint(135.0, -15.0)
end_point = QgsPoint(137.5, -16.5)
v_layer = QgsVectorLayer('LineString?crs=epsg:4326', 'line', 'memory')
pr = v_layer.dataProvider()
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([start_point, end_point]))
pr.addFeatures([ seg ])
QgsProject.instance().addMapLayers([v_layer])
iface.zoomToActiveLayer()
1
  • Hi thanks. I tried to specify CRS and nothing changed. Then I tried your code with your points in my plugin and the same thing happens: the line is created but QGIS zooms in the middle of the Ocean. I confirm that it works in the Python console, so there's a problem in my plugin. I can't understand the reason of this beavior because I simply call the function drawLine(), nothing more.
    – Lorenzo
    Jan 29 '20 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.