将Geopandas形状多边形转换为geojson

时间:2018-07-23 20:04:12

标签: python geojson geopandas

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

POLYGON: ((...))

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

shapely.geometry.mapping(shapelyObject)

返回以下内容:

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

但是当我尝试在mapbox中映射它时,它什么都不显示。我认为可能不是完全的geojson对象。

6 个答案:

答案 0 :(得分:8)

如果您不想手动创建此字典,也可以依靠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"}'

答案 1 :(得分:1)

类似这样的事情应该可以解决:

features = [{'type': 'Feature', 'properties': {}, 'geometry': shapely.geometry.mapping(shapelyObject)}]

现在,您可以尝试在Mapbox中映射features。 希望这会有所帮助。

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

答案 2 :(得分:1)

要使用熊猫编写标准的geojson对象,应按照documentation

的建议使用fiona提供的驱动程序
gdf.to_file('path/to/file.geojson', driver='GeoJSON')

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

答案 3 :(得分:0)

使用fiona提供的驱动程序:

data=shapefile.to_file("file.geojson",driver='GeoJSON')

data=geopandas.read_file("file.geojson")

data

答案 4 :(得分:0)

您也可以使用 PyShp

import shapefile

with shapefile.Reader("shapefile.shp") as shp:
    geojson_data = shp.__geo_interface__

geojson_data = shapefile.Reader("shapefile.shp").__geo_interface__

示例用法:

>>> geojson_data["type"]

'MultiPolygon'

答案 5 :(得分:-1)

Shapely返回一个python dict,其中所有坐标都在元组中。您需要转换为JSON才能使mapbox等正确接受它。

json.dumps(shapely.geometry.mapping(shapelyObject))
相关问题