GEOJSON文件的生成

  • 几何类型
    • 点(Point):如果数据是单个坐标对,如 [x, y],它代表一个点。
    • 线(LineString):如果数据是坐标对的序列,如 [[x1, y1], [x2, y2], ...],且不是闭合的,它代表一条线。
    • 多边形(Polygon):如果数据是闭合的坐标环,如 [[x1, y1], [x2, y2], ..., [x1, y1]],它代表一个多边形。对于镂空多边形,它会有多个坐标环,第一个坐标环定义外边界,其余定义内边界(镂空部分)。
    • 不相连的多个多边形(MultiPolygon):如果数据是多个这样的坐标环的集合,它代表不相连的多个多边形。
  • 构造 GeoJSON 对象
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json

def determine_geometry(coords):
    if isinstance(coords[0], (float, int)):  # Point
        return "Point", coords
    elif isinstance(coords[0][0], (float, int)):  # LineString or Polygon
        if coords[0] == coords[-1]:
            return "Polygon", [coords]
        else:
            return "LineString", coords
    elif isinstance(coords[0], list):  # MultiPolygon
        return "MultiPolygon", [coords]
    else:
        raise ValueError("Unknown geometry type")

def create_feature(name, code, parentcode, gisdata):
    geom_type, geom_coords = determine_geometry(gisdata)
    return {
        "type": "Feature",
        "properties": {"name": name, "code": code, "parentcode": parentcode}, # 附加的字段信息
        "geometry": {"type": geom_type, "coordinates": geom_coords}
    }

# 示例数据
places = [
    {"name": "地方A", "code": "001", "parentcode": "000", "gisdata": [30, 10]},  # 点
    {"name": "地方B", "code": "002", "parentcode": "000", "gisdata": [[10, 10], [20, 20], [10, 30]]},  # 线
    {"name": "地方C", "code": "003", "parentcode": "000", "gisdata": [[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]]}  # 多边形
    # 添加更多地方...
]

# 创建GeoJSON
geojson = {"type": "FeatureCollection", "features": []}
for place in places:
    feature = create_feature(place["name"], place["code"], place["parentcode"], place["gisdata"])
    geojson["features"].append(feature)

# 输出GeoJSON
print(json.dumps(geojson, indent=4))