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 on Windows and OSX called SAGA. On other platforms, you must install SAGA separately and activate it in the Processing Toolbox configuration. In PyQGIS, you can access SAGA functions through the Processing Toolbox. SAGA is yet another open source GIS that is similar to QGIS. However, both packages have strengths and weaknesses. By using SAGA through the Processing Toolbox, you can have the best of both systems.

Getting ready

In this recipe, we'll merge some building footprint shapefiles from adjoining areas into a single shapefile. You can download the sample dataset from https://geospatialpython.googlecode.com/files/tiled_footprints.zip.

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

How to do it...

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

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

How it works...

The algorithm accepts a base file and then a semicolon-separated list of additional files to be merged, and it finally accepts the output filename. The glob module creates a list of the files. To get the base file, we use the list pop() method to get the first filename. Then, we use the Python string's 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 any number of files to be merged.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset