3

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.

2
  • 1
    So you want to clip the layer to the viewport?
    – Jake
    Commented Oct 15, 2013 at 17:33
  • Yes, that's what I want to do.
    – ustroetz
    Commented Oct 15, 2013 at 17:36

2 Answers 2

4

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)

0

Create a new polygon layer: Layer-> New-> New Shapefile Layer. Draw the new polygon layer over the area of interest, then use the new layer to clip the original vector layer you want cut: Vector-> Geoprocessing Tools-> Clip.

1
  • There isn't a direct way to do that without creating an extra layer?
    – ustroetz
    Commented Oct 15, 2013 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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