Monday, 4 May 2015

qgis - How would one get the end points of a polyline?



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.



Answer



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]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...