QGIS – How to Export a Vector Layer to a New Layer and Take Extent from Canvas

exportextentsqgis

I want to create a new vector layer based on an existing one and the extent should be based on the current extent of the canvas.
How do I do that?

Edit: I am looking for a quick way to do that (a couple of clicks). I don't want to create any additional layers.

Best Answer

Running the following code in the QGIS Python console clips all features in the currently active layer with a polygon that exactly covers the current viewport, and adds the clipped features to a memory layer:

viewportPolygon = QgsGeometry().fromWkt(iface.mapCanvas().extent().asWktPolygon())
layer = iface.activeLayer()

resultlayer = QgsVectorLayer("Polygon", "result", "memory")
resultlayer.dataProvider().addAttributes(list(layer.dataProvider().fields()))

clippedFeatures = []
for feature in layer.dataProvider().getFeatures():
    clippedGeometry = feature.geometry().intersection(viewportPolygon)

    if not clippedGeometry.isGeosEmpty():
        feature.setGeometry(clippedGeometry)
        clippedFeatures.append(feature)

resultlayer.dataProvider().addFeatures(clippedFeatures)

QgsMapLayerRegistry.instance().addMapLayer(resultlayer)