将geopandas shapely polygon转换为geojson

jch*_*kow 4 python geojson geopandas

我使用geopandas创建了一个圆圈,它返回了一个形状多边形:

POLYGON: ((...))
Run Code Online (Sandbox Code Playgroud)

我想要这个相同的多边形作为geojson对象.我碰到了这个:

shapely.geometry.mapping(shapelyObject)
Run Code Online (Sandbox Code Playgroud)

返回这个:

{'type': 'Polygon', 'coordinates': (((570909.9247264927, 125477.71811034005)...}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在mapbox中映射它时,它没有显示任何内容.我想也许它不完全是一个geojson对象.

Ale*_*ers 15

Shapely 返回一个 python 字典,其中所有坐标都在元组中。您需要转换为 JSON,以便 mapbox 等...正确接受它。

json.dumps(shapely.geometry.mapping(shapelyObject))
Run Code Online (Sandbox Code Playgroud)

  • 当然,它最终就像“json.dumps()”一样简单 (2认同)

jor*_*ris 11

如果您不想手动创建此dict,还可以依赖于geopandas创建它:

In [1]: import shapely.geometry

In [2]: import geopandas

In [3]: shapely_polygon = shapely.geometry.Polygon([(0, 0), (0, 1), (1, 0)])

In [4]: geopandas.GeoSeries([shapely_polygon]).__geo_interface__
Out[4]: 
{'bbox': (0.0, 0.0, 1.0, 1.0),
 'features': [{'bbox': (0.0, 0.0, 1.0, 1.0),
   'geometry': {'coordinates': (((0.0, 0.0),
      (0.0, 1.0),
      (1.0, 0.0),
      (0.0, 0.0)),),
    'type': 'Polygon'},
   'id': '0',
   'properties': {},
   'type': 'Feature'}],
 'type': 'FeatureCollection'}
Run Code Online (Sandbox Code Playgroud)

(请注意,这会提供FeatureCollection而不是单个功能.)

或者字符串(或文件):

In [4]: geopandas.GeoSeries([shapely_polygon]).to_json()
Out[4]: '{"features": [{"bbox": [0.0, 0.0, 1.0, 1.0], "geometry": {"coordinates": [[[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]], "type": "Polygon"}, "properties": {}, "id": "0", "type": "Feature"}], "bbox": [0.0, 0.0, 1.0, 1.0], "type": "FeatureCollection"}'
Run Code Online (Sandbox Code Playgroud)

  • 我得到这个: AttributeError: 'Series' 对象没有属性 '__geo_interface__' (2认同)

Pau*_*ese 9

像这样的事情应该可以解决问题:

features = [{'type': 'Feature', 'properties': {}, 'geometry': shapely.geometry.mapping(shapelyObject)}]
Run Code Online (Sandbox Code Playgroud)

现在您可以尝试features在 mapbox 中映射。希望这可以帮助。

参考:https : //gis.stackexchange.com/questions/213717/geometry-workflow-from-shapely-to-geojson


MCM*_*MZL 8

要使用 Pandas 编写标准的 geojson 对象,您应使用文档中fiona推荐的驱动程序

gdf.to_file('path/to/file.geojson', driver='GeoJSON')
Run Code Online (Sandbox Code Playgroud)

有关import fiona; fiona.supported_drivers完全支持的驱动程序列表,请参阅