一张点位表有坐标,却缺少街道编码时,可以用行政边界给每个点补上归属。本文用北京市海淀区的一份街镇 GeoJSON 和一张五行 CSV,做一个离线命令行工具。它把唯一命中的街道写入结果表,把落在边界上的点和同时落入多个面的点留给人工核对。这样就能把可靠的街道编码接到后续汇总里,同时保留需要复查的原始坐标。
准备边界和点位
使用 Python 3.9 或以上版本,所用模块都在标准库中。把海淀区样本 110108.json 放到工作目录。这个文件的顶层是 FeatureCollection,有 29 个街镇要素,名称和编码分别在 properties.name、properties.code 中,二维边界在 geometry.coordinates 中。若使用其他文件,先确认它包含同一级的面边界,并把脚本里的字段名改成和文件一致。
在同一目录保存下面的 points.csv。第一行是列名,后两列依次是横坐标和纵坐标。点位坐标要与边界使用同一坐标系和轴顺序。首个点取自样本中的八里庄街道 centroid,其余是从真实边界构造或选取的测试坐标,可直接复制运行。
point_id,x,y
center,116.28815937803036,39.93063002530806
separate_part,116.33283054,40.01165912
hole,116.27974294,40.00732458
shared_edge,116.2703079964013,39.918841150824075
outside,116.5,39.9
新建 locate_points.py,按顺序把下面七个 Python 代码块追加到同一个文件。每块的 import、def 或 if __name__ 从行首开始,函数体保留代码块中的缩进。
第一步 导入读取文件和计算坐标所需的模块
CSV 里的坐标是文本,GeoJSON 里的坐标是 JSON 数值。两边都按十进制原值读入,再用 Fraction 做有理数运算。这样,两端点按原始小数算出的中点可以精确判在边上。
import argparse
import csv
import json
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from pathlib import Path
第二步 判断点在一个环的内部、边上还是外部
从待测点沿 x 轴正方向发出一条水平射线,从环的第一段边开始遍历。先检查点和线段是否共线,同时确认点落在线段的坐标范围内。其余情况才统计射线穿越次数。条件 (ay > y) != (by > y) 让相邻线段按半开区间处理端点,避免一次穿越在顶点处被算两遍。叉积 side 的符号结合边的方向,可以判断交点是否在点的右侧。穿越次数为奇数时,点在环内。
def ring_location(point, ring):
x, y = point
inside = False
for (ax, ay), (bx, by) in zip(ring, ring[1:]):
if not min(ay, by) <= y <= max(ay, by):
continue
side = (bx - ax) * (y - ay) - (by - ay) * (x - ax)
if side == 0 and min(ax, bx) <= x <= max(ax, bx):
return "boundary"
if (ay > y) != (by > y) and (side > 0) == (by > ay):
inside = not inside
return "inside" if inside else "outside"
第三步 用内环扣除多边形里的洞
GeoJSON 的一个 Polygon 中,第一个环是外环,后续环描述内部空洞。点须在外环里面,并且在每个内环外面,才属于该面。落在内环边上的点也记为边界。这个判断在每个 Polygon 上独立运行,所以 MultiPolygon 的每一块都可以按同样方式处理。
def polygon_location(point, polygon):
outer, *holes = polygon
location = ring_location(point, outer)
if location != "inside":
return location
for hole in holes:
location = ring_location(point, hole)
if location == "boundary":
return "boundary"
if location == "inside":
return "outside"
return "inside"
第四步 读入街道编码和边界
将 Polygon 包成只有一个元素的列表,MultiPolygon 直接保留原列表。这样后面可以统一遍历各块。读取时检查编码是否重复、坐标是否为二维数值,以及环是否首尾闭合。
def load_regions(path):
with path.open(encoding="utf-8") as file:
data = json.load(file, parse_float=Fraction)
if not isinstance(data, dict) or data.get("type") != "FeatureCollection":
raise ValueError("边界文件必须是非空 FeatureCollection")
features = data.get("features")
if not isinstance(features, list) or not features:
raise ValueError("features 必须是非空数组")
regions = []
seen = set()
for feature in features:
properties = feature["properties"]
code = str(properties["code"])
if code in seen:
raise ValueError(f"重复的行政编码 {code}")
seen.add(code)
geometry = feature["geometry"]
kind, coordinates = geometry["type"], geometry["coordinates"]
if kind not in ("Polygon", "MultiPolygon"):
raise ValueError(f"{code} 的几何类型不受支持:{kind}")
polygons = [coordinates] if kind == "Polygon" else coordinates
if not polygons or any(not polygon for polygon in polygons):
raise ValueError(f"{code} 含空多边形")
for polygon in polygons:
for ring in polygon:
if len(ring) < 4 or ring[0] != ring[-1]:
raise ValueError(f"{code} 的边界环至少需要四项且首尾相同")
if any(len(point) != 2 or any(type(v) not in (int, Fraction) for v in point)
for point in ring):
raise ValueError(f"{code} 的边界坐标必须是二维数值")
regions.append((code, properties["name"], polygons))
return regions
第五步 汇总一个点的所有命中
即使先找到一个内部命中,也要继续检查其他区域。共边可能对应两个编码,叠合的面也可能同时包含同一点。结果优先标记 boundary,其次是 overlap,两种情况都只填候选编码。唯一的内部命中才标为 matched,并写入街道编码和名称。所有区域均未命中时记为 outside。
def locate(point, regions):
interiors, boundaries = [], []
for code, name, polygons in regions:
locations = {polygon_location(point, polygon) for polygon in polygons}
if "boundary" in locations:
boundaries.append((code, name))
elif "inside" in locations:
interiors.append((code, name))
candidates = sorted(code for code, _ in interiors + boundaries)
joined = "|".join(candidates)
if boundaries:
return "boundary", "", "", joined
if len(interiors) > 1:
return "overlap", "", "", joined
if interiors:
code, name = interiors[0]
return "matched", code, name, joined
return "outside", "", "", ""
第六步 逐行读取点位表
按原有行序读取编号和坐标,将分类结果追加到同一行。utf-8-sig 同时支持普通 UTF-8 和带 BOM 的 CSV。如果某行的坐标缺失或无法解析,报错会带行号,方便直接找到原始记录。
def classify_csv(path, regions):
results = []
with path.open(encoding="utf-8-sig", newline="") as file:
reader = csv.DictReader(file)
columns = ("point_id", "x", "y")
if not set(columns).issubset(reader.fieldnames or []):
raise ValueError("点位 CSV 需要 point_id,x,y 三列")
for row in reader:
point_id, x, y = (row[column] for column in columns)
if not point_id or not point_id.strip():
raise ValueError(f"CSV 第 {reader.line_num} 行缺少点位编号")
try:
point = (Fraction(Decimal(x)), Fraction(Decimal(y)))
except (InvalidOperation, ValueError, OverflowError, TypeError) as exc:
raise ValueError(f"CSV 第 {reader.line_num} 行坐标必须是有限小数") from exc
results.append((point_id, x, y, *locate(point, regions)))
return results
第七步 接好命令行入口
三个参数依次是边界文件、点位表和结果表。脚本先完成所有点的判定,再用 x 模式创建 CSV。同名文件已存在时,换一个输出文件名即可保留前次结果。
def main():
parser = argparse.ArgumentParser(description="使用 GeoJSON 批量匹配坐标归属")
parser.add_argument("boundary", type=Path)
parser.add_argument("points", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
try:
regions = load_regions(args.boundary)
results = classify_csv(args.points, regions)
with args.output.open("x", encoding="utf-8", newline="") as file:
writer = csv.writer(file)
writer.writerow(("point_id", "x", "y", "status", "region_code",
"region_name", "candidate_codes"))
writer.writerows(results)
except (OSError, KeyError, TypeError, ValueError) as exc:
parser.exit(1, f"处理失败:{exc}\n")
print(f"已检查 {len(regions)} 个区域、{len(results)} 个点位,结果写入 {args.output}")
if __name__ == "__main__":
main()
运行并核对结果
在三个文件所在的目录运行以下命令。第一次运行时,输出文件 result.csv 应尚不存在。
python3 locate_points.py 110108.json points.csv result.csv
本次运行显示检查了 29 个区域、5 个点位。打开 result.csv,可按 point_id 逐行核对:
| 点位 | 状态 | 街道或候选编码 |
|---|---|---|
center | matched | 八里庄街道 110108005 |
separate_part | matched | 东升镇 110108024 |
hole | matched | 燕园街道 110108015 |
shared_edge | boundary | 110108001 和 110108005 |
outside | outside | 空 |
separate_part 位于东升镇的第二块面内。hole 在青龙桥街道的外环内,同时也在该面的内环里,所以青龙桥街道被排除,点最终匹配到填在这个洞里的燕园街道。shared_edge 使用八里庄街道与万寿路街道共用的一段边的中点,因此只写两个候选编码。导入台账时,可以先按 matched 的 region_code 汇总,再按点位编号回查其余行。
常见问题
点看着很靠近一条边,为什么仍然有唯一归属? boundary 只表示坐标精确落在原始线段上。经过取整或坐标转换的点可能位于线段一侧。业务需要把边界附近的点也纳入复核时,可以先统一到适合测距的投影坐标系,再另设带单位的距离阈值。
一批点都显示 outside 怎么排查? 先确认边界文件覆盖了点位所在区县,再检查 x、y 的列顺序和两份数据的坐标系。可以先用一个已知位于区域内部的控制点排查。属性里的 centroid 只提供候选坐标,凹面或多面要素的中心坐标可能落在面外,仍应执行面内判定。
数据与源码
- 省市区县边界入口见 GeoJSON 地图数据。复现街镇示例请使用配套的海淀区样本。
- 将生成的归属结果接入地图时,可参考既有的 ECharts 地图展示示例项目 echarts-map-demo。
locate_points.py由本文七段代码组成。
4万+




被折叠的 条评论
为什么被折叠?



