7

I am attempting to write a script to get the end points of a series polylines, and then use those end points to create a polygon. I'm not sure which tools to begin to use on this project.

I would prefer to use QGIS or even better a python script using open source tools.

ahmadhanb
  • 40,826
  • 5
  • 51
  • 105
Ryan Bertram
  • 191
  • 3
  • 12
  • This is a similar post which outlines retrieving the end nodes of a street segment in qGIS: http://gis.stackexchange.com/questions/28092/is-there-any-way-to-extract-coordinates-of-a-road-segment-using-qgis – evv_gis Feb 10 '14 at 18:21

2 Answers2

13

It is easier with Fiona, more "Pythonic", and list slicing:

import fiona
with fiona.drivers():
   for line in fiona.open("some_shapefile.shp"):
         # print first and last point of every line
         print line['geometry']['coordinates'][0], line['geometry']['coordinates'][-1]

And with shapely:

from shapely.geometry import Point
for line in fiona.open("some_shapefile.shp"):
   print Point(line['geometry']['coordinates'][0]), Point(line['geometry']['coordinates'][-1])

And you can construct you polygon and save it with Fiona

New: using the suggestion of sgillies (boundary) with the shape function of shapely

from shapely.geometry import shape
for line in fiona.open("some_shapefile.shp"):
     print shape(line['geometry']).boundary[0], shape(line['geometry']).boundary[1]
gene
  • 54,868
  • 3
  • 110
  • 187
  • 1
    Gene, the boundary() method of a Shapely object might be more reliable. See http://toblerity.org/shapely/manual.html#MultiLineString. – sgillies Feb 10 '14 at 21:38
  • Great answer, gene. Just one correction, the boundary of the MultiLineString could have more than 2 points if it is complex. – César Argul García Feb 11 '14 at 10:16
  • @gene great answer, thank you! How can I store these points in another shapefile instead of print using shapely? – GeoSal Jul 22 '16 at 07:43
5

You can do this with the GDAL/OGR python bindings. Here's a link to the OGR API tutorial.

A worked example:

from osgeo import ogr

ds=ogr.Open(somepolylines)
lyr=ds.GetLayer()
for i in range(lyr.GetFeatureCount()):
    feat=lyr.GetFeature(i)
    geom=feat.GetGeometryRef()
    firstpoint=geom.GetPoint(0)
    lastpoint=geom.GetPoint(geom.GetPointCount()-1)
    print firstpoint[0],firstpoint[1],lastpoint[0],lastpoint[1] #X,Y,X,Y
user2856
  • 65,736
  • 6
  • 115
  • 196