Polygon → Polyline using pyshp

Well, I’ve been on a bit of a hiatus from this blog, thanks in large part to switching jobs and cities. But, I’ll try to fit posts in here and there as time allows.

Since ArcGIS licenses come at a premium (i.e. not everyone gets one), I am often tasked with performing file conversions that are difficult to perform outside the ArcGIS environment (and without the help of arcpy). So, in my quest for efficency (or laziness, whichever you choose), I am attempting to write a script that will take polygon shapefiles, convert to one line shapefile, and output the lines to a GPX file for upload to a GPS unit. The ultimate goal is to use py2exe to make a standalone application in which users can upload their own polygon shapefile and output a GPX file, and leave me out of it (not that I mind, but I’d rather focus on analysis).

Here’s what I’ve got so far. It deconstructs a polygon shapefile to individual vertices and outputs a line shapefile, using the pyshp library. Next steps involve installing GDAL, figuring out how to convert the shapefile to GPX, and packaging it all up with py2exe for distribution.

# import the shapefile library
import shapefile
# path to input polygon shapefile
infc = shapefile.Reader(r"C:\users\dwiens\GIS_Data\testpoly")
# create a shapefile writer
outfc = shapefile.Writer(shapefile.POLYLINE)
# turn geometry/attribute autoBalanace on
outfc.autoBalance = 1
# add a field, any field
outfc.field('FIELD','C','1')
# get the input geometries
shapes = infc.shapes()
# create empty arrays to hold line parts and vertices
linePoints = []
lineParts = []
# loop through shapes
for shape in shapes:
  # loop through each vertex
  for point in shape.points:
    # add each vertex to array
    linePoints.append(point)
  # add vertex array to shape array
  lineParts.append(linePoints)
  #empty the vertex array, move to next shape
  linePoints = []
# encode coordinates as a line
outfc.line(parts=lineParts)
# add blank value as a record
outfc.record('')
# save the shapefile
outfc.save(r"C:\users\dwiens\GIS_Data\testline")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s