[GIS] Creating Polyline from GML using PyShp

gmllinepyshppython

I have a problem in creating some polylines in one Shapefile with PyShp 1.2.
The plan is to read a GML file containing LineStrings and create a shapefile.

The theory is clear, but the realworld is different.
As I understand the syntax is as follows:

w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])

This one is a fixed line, but my lines are flexible.
My thoughts were, to extract the Coordinates from the GML file and concatenate it to a String which meets the PyShape Syntax.
My results are therefore:

[[[-94,-49.1152],[-94.45451,-49], …. ,[-93,-49.30391],[-94,-49.1152]]] <– named "coords"

The idea in using s.line(parts=coords) failed due to needed float values.

The question here is, how to meet the syntax and stay flexible in the same way.
Maybe my Python skills are still too basic, but the following links did not help:

Using pyshp to convert .csv file to .shp? <– used points

Unable to create shapefile using shapefile.py
<– used also points

Using PyShp to convert polygons in *.csv to *.shp files? <– comes close, but is fixed due to rectangles

Long story short: How can i create a polyline shape with lines of different length, based on coordinates available in variables.

I know that there are additional lines nessecary, but those are not the problem.

Best Answer

Matthias,

The pyshp syntax requires nested Python lists containing coordinates as floats. Your current approach is a string which simply looks like the syntax.

The quick, but not recommended, method would be to eval your string (very insecure):

linestr = "[[[-94,-49.1152],[-94.45451,-49],[-93,-49.30391],[-94,-49.1152]]]"
w.line(parts=eval(linestr))

The proper way would be to cast each coordinate pair to floats and append to a list:

coords=[["-94","-49.1152"],["-94.45451","-49"],["-93","-49.30391"],["-94","-49.1152"]]
line_parts = []
line = []
for x,y in coords:
    line.append([float(x),float(y)])
line_parts.append(line)
w.line(parts=line_parts)
Related Question