QGIS Python Programming Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Performing a union on vector shapes

A union turns two overlapping shapes into one. This task can be easily accomplished with the Processing Toolbox. In this recipe, we'll merge the outline of a covered building to the footprint of the main building.

Getting ready

You can download the building files from the following URL and extract them to a directory named /qgis_data/union:

https://github.com/GeospatialPython/Learn/raw/master/union.zip

How to do it...

All we need to do is run the qgis:union algorithm:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. Import the processing module:
            import processing 
    
  4. Now, run the algorithm specifying the two input shapes and the single output file:
            processing.runandload("qgis:union",
                                  "/qgis_data/union/building.shp",
                                  "/qgis_data/union/walkway.shp",
                                  "/qgis_data/union/union.shp") 
    

How it works...

As you can tell from the structure of the command, this tool can only combine two shapes at once. It finds where the two geometries meet, and then removes the overlap joining them at the meeting point.

In the original data, the layers starts out as two distinct shapes, as shown in this image:

How it works...

Once the union is complete, the shapes are now one shapefile with the overlap being a separate feature, as shown in this image:

How it works...