Thursday, March 26, 2009

Converting a shapefile into one kml file per feature

Below is some python/GDAL code for an easy way to split a GIS shapefile (such as those found in the CA Statewide Database) into a bunch of kml files, one for each feature found in the file. For example, this can be used to create individual precinct maps from the county and whole state files in the SWDB, which can then be rendered in either Google Earth or Google Maps.


This code is a long way from perfect; it's finding some MultiPolygons where there should be polygons, and GDAL barfs out some missing symbol errors (but keeps on truckin' anway). But I didn't see a ready solution for this posted elsewhere, so enjoy (sharp sytax highlighting via http://pygments.org/):



There are a bunch of different ways to get into the guts of a shapefile and start mucking around with it. If you have an ESRI ArcMap license you can sort through the numerous ESRI .Net APIs, which is how I've ordinarily done it. But it can be slow going, and you do need the license. As far as I can tell this has to be the easiest, fastest way to get there with open source. And writing python is a lot more fun C# or VB anyway.


If you'd like to try this at home, this GDAL API tutorial from the geodjango site is invaluable. And if you're on a Mac, for the love of all that is holy don't try to compile GDAL and all its dependencies. Download the "KyngChaos Binaries" instead. Yes, they sound like warez but they seem to work fine and will save you hours of wandering through Makefiles.

1 comment:

gene said...

"They sound like warez" ????
All the binaries are opensource and free