[GIS] Sub-dividing KML files

kmlqgis

I have a KMZ file of north-eastern Thailand which marks the boundaries of a larger district and it's sub-districts. Still new to GIS and in the process of getting familiar with QGIS, I wonder can anyone advise me how can I "extract" the boundaries of each of these sub-districts from that KMZ?

E.g. are there any QGIS plugins which could be used for this task?

Best Answer

OK, so step 1 (getting the outline of all of them) is nice and easy. All you need is to go in QGIS to

Vector->Geoprocessing Tools->Dissolve

Which will open the dialog for the "Dissolve" tool.

Set your layer as the "Input Vector Layer", select a "Dissolve Field" that is the same for all of the features in the layer (I chose "tesellate"), create a location for the output shapefile, and tick "add result to canvas" like this...

enter image description here

Press "OK" and it will dissolve all of your features into one big one:

enter image description here

Close the dissolve tool.

Next, simply convert it to a KML/KMZ by right clicking on it in the "Layers" list (normally on the left of the screen), click "Save As", and set the format to "KML".

Done!

I'm afraid that splitting each feature to separate KML layers is a little more complex, and will require some scripting...

I recommend downloading the "Script Runner" plugin, and then run this code:

"""
    Explode a Shapefile CAD-style - each feature will become a new file.
"""

from qgis.core import *
import qgis.utils

class VectorExploder:
     def __init__(self, iface):

        #self.iface = iface

        # Load the layer
        inPath = "[PATH TO YOUR DATA]/NE_admin.kmz"
        outDirectory = "[OUTPUT DIRECTORY PATH]/"
        print inPath
        layer = QgsVectorLayer(inPath, "NE_admin", "ogr")
        if not layer.isValid():
            print "Layer failed to load!"
            return

        # Get the index of the 'Name' attribute
        idx = layer.fieldNameIndex('Name')

        # Loop through all of the features, saving each to file
        iter = layer.getFeatures()
        for feature in iter:

            #get the field list
            fields = feature.fields()
            featureName = feature.attributes()[idx]
            fileName = featureName.encode('utf8', 'replace')

            # create an instance of vector file writer, which will create the vector file.
            outPath = outDirectory + fileName + ".kml"
            #outPath = outDirectory + str(feature.id()) + ".kml"
            print outPath
            crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.PostgisCrsId)
            writer = QgsVectorFileWriter(outPath, "CP1250", fields, QGis.WKBPoint, crs, "KML")
            if writer.hasError() != QgsVectorFileWriter.NoError:
              print "Error when creating shapefile: ", writer.hasError()
              return

            # Load the feature into the writer
            writer.addFeature(feature)

            # delete the writer to flush features to disk (optional)
            del writer

def run_script(iface):
        exp = VectorExploder(qgis.utils.iface)

All you need to do first is add in your input file (instead of "[PATH TO YOUR DATA]") path and output directory (instead of "[OUTPUT DIRECTORY PATH]"), then save the file as a Python (.py) file somewhere. Then open the Script Runner plugin, load in the file (by pressing the "+" button) and press "Run Script".

This will separate every feature in your dataset (>2678 of them!) into a separate KML file. They will all be numbered, as my computer can't handle the encoding of the names, but I've left the code in there if you want to use names instead. Just swap the # from the line that starts "outfile" to the line below (also starting "outfile").

You can run this again and again for each of your datasets.

How's that?

Related Question