地图相关工具函数 --- 判断某坐标属于哪个省份

1. 地图边界数据集

使用 static/map/china.json 即可

2. 模块下载

pip install shapely

3. 代码实现

from shapely.geometry import Point, Polygon
import json


def point_of_which_province(query_point):
    """
    坐标点属于哪个省份: 通过多边形判断算法, 来计算坐标点是否在某省份的多边形区域内
    :param query_point: 要查询的坐标点格式: (119.257591, 31.542629)
    :return: 如果查到了该坐标点属于某省份, 则返回省份名称字符串, 否则返回空字符窜
    """

    # 读取中国边境线的数据
    with open('china.json', encoding="utf-8") as f:
        border_data = json.load(f)

    # 获取边境线的多边形对象
    border_polygons = {}
    for feature in border_data['features']:
        if feature["properties"]["name"] not in border_polygons:
            border_polygons[feature["properties"]["name"]] = []

        # 内蒙古自治区是三维数组, 其他省份均是四维数组, 所以要特殊处理一下
        if feature["properties"]["name"] == "内蒙古自治区":
            border_polygons[feature["properties"]["name"]] = Polygon(feature['geometry']['coordinates'][0])
        else:
            border_polygons[feature["properties"]["name"]] = Polygon(feature['geometry']['coordinates'][0][0])

    # 查询传入的坐标点是否在多边形区域内
    point = Point(query_point[0], query_point[1])
    for name, polygon in border_polygons.items():
        if polygon.contains(point):
            return name
    return ''


# 使用示例
print(point_of_which_province((119.257591, 31.542629)))  # 北京市的经纬度

posted @ 2024-10-10 16:14  河图s  阅读(91)  评论(0)    收藏  举报