[GIS] Zooming to selected feature using PyQGIS

featurespyqgisselectzoom

I want to create a function that selects a feature and zooms to it (similar in QGIS). Therefore there is following function:

QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)

def zoomTo(self):
    layer = self.vlayer
    atable = self.ui.table
        
    selectList=[]
    for i in atable.selectionModel().selectedRows():
        ID = atable.item(i.row(),0).text()
        selectList.append(int(ID))
  
    layer.setSelectedFeatures(selectList)

The selected features are highlighted on the map. But I have no idea how to make a "zoom" to the selected features or some kind of focus them in the middle of the map.

Best Answer

You need to set the extents of the map canvas to the extents of the selections:

box = layer.boundingBoxOfSelected()
iface.mapCanvas().setExtent(box)
iface.mapCanvas().refresh()
Related Question