19

I'm having a little trouble with the Python OGR API. What I am trying to do is get all the coordinates of each vertex of the outer ring of a polygon.

This is what I have so far:

import osgeo.ogr
import glob

path = "/home/woo/maps/"
out = path + 'output.txt'

file = open(out,'w')
for filename in glob.glob(path + "*.shp"):
    ds = osgeo.ogr.Open(filename)
    layer1 = ds.GetLayer(0)
    print layer1.GetExtent()    
    for feat in layer1:
        geom = feat.GetGeometryRef()
        ring = geom.GetGeometryRef(0)
        points = ring.GetPointCount()
        #Not sure what to do here


file.close()

I have heard that you can just for over the region but that only returns the rings in the polygon, not the nodes.

Anyone able to help.

whuber
  • 69,783
  • 15
  • 186
  • 281
Nathan W
  • 34,706
  • 5
  • 97
  • 148

4 Answers4

17

It depends a bit on your file format and geometry, but in principle the continuation could look like this.

  for p in xrange(points):
        lon, lat, z = ring.GetPoint(p)
Nathan W
  • 34,706
  • 5
  • 97
  • 148
relet
  • 1,459
  • 12
  • 19
7

FYI - for a complete code example based on the original question, and a script you can use right away .. see https://github.com/spatialguru/NME/blob/master/ogr_explode.py

1tylermitchell
  • 121
  • 2
  • 2
6

I just ran into the same problem. I ended using the ExportToJson function in ogr and then reading the Json string into a dictionary. Using my data and the notation from the original question, this looks like:

import json
...
ring_dict = json.loads(ring.ExportToJson())
ring_dict

{'coordinates': [[-4.94237, 55.725449],
  [-4.941922, 55.725585],
  [-4.9420024, 55.7252119],
  [-4.9422001, 55.7250997],
  [-4.9423197, 55.7251789],
  [-4.9425472, 55.7253089],
  [-4.94237, 55.725449]],
 'type': 'LineString'}
David M
  • 61
  • 1
  • 2
4

If you're looking just at shapefiles, you could also use pyshp.

import shapefile
sf = shapefile.Reader("shapefiles/blockgroups")
shapes = sf.shapes()
for shape in shapes:
  for vertex in shape.points:
    #do something with the vertex
Marc Pfister
  • 4,097
  • 17
  • 11