在 Python 中使用 GeoJSON:点、线和多边形

概述

GeoJSON 是一种使用 JavaScript 对象表示法(JSON)编码各种地理数据结构的格式。本技术文档概述了如何在 Python 中处理 GeoJSON 对象,特别是重点介绍点(Point)、线(LineString)和多边形(Polygon)在 GeometryCollection 中的使用。

GeoJSON 结构

GeoJSON 对象可以表示各种几何形状,例如点、线串和多边形。这些几何形状可以在 GeometryCollection 中组合使用。

示例 GeoJSON 对象

gc = {
    "type": "GeometryCollection",
    "geometries": [
        {
            "type": "Point",
            "coordinates": [-89.33, 30]
        },
        {
            "type": "LineString",
            "coordinates": [
                [-89.33, 30.3], [-89.36, 30.28]
            ]
        },
        {
            "type": "Polygon",
            "coordinates": [
                [
                    [-89.33167167, 29.96], [-89.25914630, 29.96], 
                    [-89.25914630, 30], [-89.33167167, 30],
                    [-89.33167167, 29.96]
                ]
            ]
        }
    ]
}

print(gc)

详细解读

  1. GeometryCollection:包含多个几何图形的根对象。
    • type:指定 GeoJSON 对象的类型,对于集合来说,是 "GeometryCollection"
    • geometries:一个包含各个几何对象的数组。
  2. Point:表示坐标空间中的单个位置。
    • type"Point"
    • coordinates:一个包含两个数字的数组,表示经度和纬度。
  3. LineString:表示一系列连接的线段。
    • type"LineString"
    • coordinates:一组坐标对的数组,每对坐标代表线上的一个点。
  4. Polygon:表示由一系列线环定义的闭合区域。
    • type"Polygon"
    • coordinates:线环坐标的数组,每个线环是一个坐标对的数组。第一个和最后一个坐标对必须相同以闭合多边形。

在 Python 中创建 GeoJSON 对象

要在 Python 中创建和操作 GeoJSON 对象,可以使用字典来构建数据,如上面的示例所示。以下是创建每种几何图形的分步说明。

创建一个点

point = {
    "type": "Point",
    "coordinates": [-89.33, 30]
}

创建一个线串

linestring = {
    "type": "LineString",
    "coordinates": [
        [-89.33, 30.3], [-89.36, 30.28]
    ]
}

创建一个多边形

python复制代码polygon = {
    "type": "Polygon",
    "coordinates": [
        [
            [-89.33167167, 29.96], [-89.25914630, 29.96],
            [-89.25914630, 30], [-89.33167167, 30],
            [-89.33167167, 29.96]
        ]
    ]
}

将几何图形组合到 GeometryCollection 中

geometry_collection = {
    "type": "GeometryCollection",
    "geometries": [point, linestring, polygon]
}

打印 GeometryCollection

要以人类可读的格式打印 GeometryCollection 对象,可以使用 print 函数:


print(geometry_collection)

结论

GeoJSON 是表示地理数据的强大格式。通过上述方法在 Python 中构建数据,您可以创建复杂的几何图形和几何图形集合。本文档介绍了在 GeometryCollection 中创建点、线串和多边形,为在 Python 中处理地理数据提供了基础。