3

using the pyshp library (https://code.google.com/p/pyshp/) I am trying to create a "complex" polgon with one hole inside the main-poly plus one island-poly. It should look like this:

enter image description here

I used the following code from the documentation, only changing the number of points and using anticlockwise rotation for the hole:

import shapefile
w = shapefile.Writer(shapefile.POLYGON)
w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50],[10,40],[10,10],[30,10],[30,40],[10,40],[70,20],[100,20],[100,0],[70,0],[70,20]]])
w.field('FIRST_FLD','C','40')
w.field('SECOND_FLD','C','40')
w.record('Poly','PolyTest')
w.save('TESTPOLY')

I get this: enter image description here

6

Each piece of your complex polygon, including the hole, is called a "part" in the shapefile spec. Parts are how they tie multiple distinct geometries to a single dbf record.

In pyshp, parts are a list of lists passed to the poly method. The example you followed only has one list of points within the parts. But your shapefile has 3 distinct polygons. So each one of your 3 shapes needs to be in a sub-list like this:

w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50]],[[10,40],[10,10],[30,10],[30,40],[10,40]],[[70,20],[100,20],[100,0],[70,0],[70,20]]])

enter image description here

0
# [[[Clockwise Part (Single)]], [[Counter Clockwise Parts (Multiple)]]]
parts_with_holes = [[[0, 50], [50, 50], [50, 0], [0, 0], [0, 50]], [[10, 40], [10, 10], [30, 10], [30, 40], [10, 40]]]
# [[Clockwise Part (Single)]]
parts_no_holes = [[10, 10], [10, 40], [30, 40], [30, 10], [10, 10]]

sf_out.field('FIRST_FLD', 'C', '40')
sf_out.field('SECOND_FLD', 'C', '40')

sf_out.poly(parts_with_holes)
sf_out.record('Poly', 'PolyTest')

sf_out.poly([parts_no_holes])
sf_out.record('Poly', 'PolyTest')
sf_out.close()

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

  • 1
    Welcome to GIS.SE. Please consider adding explanation of your code in the answer. – tinlyx Apr 6 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.