首页 > 解决方案 > 将geopandas shapely 多边形转换为geojson

问题描述

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

POLYGON: ((...))

我想要这个与 geojson 对象相同的多边形。我遇到了这个:

shapely.geometry.mapping(shapelyObject)

它返回这个:

{'type': 'Polygon', 'coordinates': (((570909.9247264927, 125477.71811034005)...}

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

标签: pythongeojsongeopandas

解决方案


如果你不想手动创建这个字典,你也可以依赖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'}

(请注意,这给出了 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"}'

推荐阅读