首页 > 解决方案 > Python Shapely 似乎为多边形分配了错误的点

问题描述

我正在使用 shapely 将坐标映射到 geojson 文件,但似乎映射是错误的。在下图中(来自 geojson.io),您可以看到多边形,黄色是我要映射的点。在这种情况下,匀称地告诉我该点位于多边形内部,但正如您所见,这是错误的。

在此处输入图像描述

我的代码:

import json
from shapely.geometry import shape, Point

upzs = open('upzs.geojson', encoding='utf-8')
upzs = json.load(upzs)

point = Point(-74.09008026123047,4.719461869021348) # longitude, latitude

for feature in upzs['features']:
    polygon = shape(feature['geometry'])
    if point.within(polygon) == True:
        print(feature['properties']['NOMBRE'])
    if polygon.contains(point):
        print(feature['properties']['NOMBRE'])

我的输出:

EL RINCON
EL RINCON

('EL RINCON' 是错误多边形的名称)

如果您想测试它,您可以从此链接下载 geojson 文件

标签: pythongisshapely

解决方案


您确定您发布的图像真的是 GeoJson 文件中的 EL RINCON 吗?

当我在 jupyter notebook 上运行以下内容时,我得到了一个非常不同的形状。

import json
from shapely.geometry import shape, Point

upzs = open('pensionadosactivosupz.geojson', encoding='utf-8')
upzs = json.load(upzs)

point = Point(-74.09008026123047,4.719461869021348) # longitude, latitude

for feature in upzs['features']:
    polygon = shape(feature['geometry'])
    if point.within(polygon) == True:
        print(feature['properties']['NOMBRE'])
    if polygon.contains(point):
        print(feature['properties']['NOMBRE'])
        display(polygon)

在此处输入图像描述

此外,如果我映射该点(使用其他包,都在 pip 上可用),则该点包含在多边形中。找到底部的白色圆圈。

import matplotlib.pyplot as plt
import mplleaflet
import geopandas as gpd
from shapely.geometry import shape, Point
p = Point(-74.09008026123047,4.719461869021348)

x = gpd.read_file("pensionadosactivosupz.geojson")

fig, ax = plt.subplots()
x[x.NOMBRE=="EL RINCON"].plot(ax=ax)
ax.scatter([-74.09008026123047], [4.719461869021348], c="white")
mplleaflet.show()

在此处输入图像描述


推荐阅读