我正在阅读GeoJSON文件,其中包含我制作的两个简单多边形描述以及来自http://ryanmullins.org/blog/2015/8/18/land-area-vectors-for-geographic-combatant-commands的六个复杂向量
我可以阅读自己对Shapely Polygons的4-8点描述。但是,上面网站上更复杂的描述给出了以下错误:
from shapely.geometry import Polygon
jsonFile="path/to/file.json"
with open(jsonFile) as f:
data=json.load(f)
for feature in data['features']:
#This is not how I'm saving the polygons, and is only for testing purposes:
myPoly=Polygon(feature['geometry']['coordinates'])
错误消息:
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 229, in __init__
self._geom, self._ndim = geos_polygon_from_py(shell, holes)
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 508, in geos_polygon_from_py
geos_shell, ndim = geos_linearring_from_py(shell)
File "/.../anaconda2/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 454, in geos_linearring_from_py
assert (n == 2 or n == 3)
AssertionError
它们被读作列表,USAFRICOM的长度为113。
有没有办法将这些非常长的矢量读成形状?我尝试过Polygon,MultiPoint,asMultiPointIf。如果没有,您能否建议如何将此矢量描述简化为可由Shapely读取的内容?
答案 0 :(得分:0)
嗯,它比一次性抛出Shapely的所有坐标要复杂得多。
根据关于多重多边形的GeoJSON spec和Shapely's documentation:多边形由多边形数组组成,多边形再次由描绘外部和内部区域/孔的线性环组成。
这是我尝试使用MultiPolygon阅读器获取GeoJSON文件,在QGIS中打开输出正确显示,如果您有问题,请告诉我。
import json
from shapely.geometry import mapping
from shapely.geometry import Polygon
from shapely.geometry import LinearRing
from shapely.geometry import MultiPolygon
jsonFile = "USCENTCOM.json"
polygons = []
with open(jsonFile) as f:
data = json.load(f)
for feature in data['features']:
for multi_polygon in feature['geometry']['coordinates']:
# collect coordinates (LinearRing coordinates) for the Polygon
tmp_poly = []
for polygon in multi_polygon:
tmp_poly.append(polygon)
if len(tmp_poly) > 1:
# exterior LinearRing at [0], all following interior/"holes"
polygons.append(Polygon(tmp_poly[0], tmp_poly[1:]))
else:
# there's just the exterior LinearRing
polygons.append(Polygon(tmp_poly[0]))
# finally generate the MultiPolygon from our Polygons
mp = MultiPolygon(polygons)
# print GeoJSON string
print(json.dumps(mapping(mp)))