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

Merging shapefiles

Merging shapefiles with matching projections and attribute structures is a very common operation. In QGIS, the best way to merge vector datasets is to use another GIS system included with QGIS, called SAGA. The OSGeo4W QGIS version for Windows includes SAGA. The KyngChaos distribution of QGIS for OSX includes SAGA. Most other versions and platforms will need SAGA manually installed. In PyQGIS, you access SAGA functions through the Processing Toolbox.

Getting ready

In this recipe, we'll merge some building footprint shapefiles from the adjoining areas into a single shapefile. You can download the sample dataset from the following URL:

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

Extract the zipped shapefiles to a directory named /qgis_data/tiled_footprints.

How to do it...

We will locate all of the .shp files in the data directory and hand them to the saga:mergeshapeslayers to merge them:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. We will import the Python glob module for wildcard file matching:
            import glob 
    
  4. Next, we import the processing module for the merge algorithm:
            import processing 
    
  5. Now, we'll specify the path of our data directory:
            pth = "/qgis_data/tiled_footprints/" 
    
  6. Next, we'll locate all the .shp files:
            files = glob.glob(pth + "*.shp") 
    
  7. Then, we specify the output name of the merged shapefile:
            out = pth + "merged.shp" 
    
  8. Finally, we run the algorithm that will load the merged shapefile onto the map:
            processing.runandload("saga:mergeshapeslayers",files.pop(0),
                                  ";".join(files),out) 
    

How it works...

The algorithm accepts a base file and then a semi-colon-separated list of additional files to be merged, and finally the output file name. The glob module creates the list of files. To get the base file, we use the list pop() method to remove and get the first filename. Then, we use the Python string join() method to make the required delimited list for the rest.

There's more...

QGIS has its own merge method available through the processing module, called qgis:mergevectorlayers, but it is limited because it only merges two files. The SAGA method allows for any number of files to be merged.