Search code examples
pythongeometrygeopandasshapefilemultilinestring

How to turn Shapefile into list of lists of coordinates python?


I have a shapefile that creates a map using a set of longitude and latitude points. I am very unexperienced with these files and don't know how to work with them. I need to convert this shapefile into a list of lists, with each internal list formatted latitude, longitude.

I tried this, but was fed a list of Multi line strings, which I have been unable to turn into a set of points

import geopandas as gpd

shapefile_path = 'Users/user/downloads/ne_50m_coastline/ne_50m_coastline.shp'
gdf = gpd.read_file(shapefile_path + 'ne_50m_coastline.shp')
coastline_points = gdf['geometry'].tolist()

The result was this:

[<LINESTRING (180 -16.153, 179.848 -16.214, 179.789 -16.221, 179.715 -16.208,...>, <LINESTRING (177.258 -17.054, 177.287 -17.049, 177.276 -17.105, 177.234 -17....>, <LINESTRING (127.373 0.791, 127.354 0.847, 127.32 0.862, 127.293 0.842, 127....>, <LINESTRING (-81.322 24.685, -81.42 24.75, -81.422 24.733, -81.379 24.666, -...>, <LINESTRING (-80.799 24.846, -80.839 24.818, -80.848 24.804, -80.829 24.804,...>, etc. ]

Every solution I've tried to convert this into a list of lists has resulted in this outcome: 'MultiLineString' object is not iterable

would love some help, thanks!!


Solution

  • You can convert multi-part geometries (like MultiLineString) into single geometries (like LineString) using the explode method. That allows us to write:

    import geopandas as gp
    
    gdf = gp.read_file('ne_50m_coastline.shp')
    
    coords = []
    for geom in gdf.explode()['geometry']:
        coords.append(list(geom.coords))
    

    At the conclusion of this code, the coords variable contains a list of lists of coordinates:

    [
      [
        [
          180.0,
          -16.152929687500006
        ],
        [
          179.84814453125,
          -16.21425781250001
        ],
        .
        .
        .
      ],
      [
        [
          177.25751953125,
          -17.05419921875
        ],
        [
          177.28740234375005,
          -17.048632812500003
        ],
        [
          177.27578125000002,
          -17.10488281250001
        ],
        .
        .
        .