You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助GeoDjango与PostGIS检测两个多边形是否存在公共内部点

在GeoDjango+PostGIS中检测多边形是否存在公共内部点

要实现你描述的检测逻辑(仅边相交/不相交返回False,有公共内部点/多边形相等返回True),可以结合GeoDjango中几何体的intersects和touches方法,对应PostGIS的ST_Intersects和ST_Touches函数:

核心逻辑

  • intersects(a, b):判断两个多边形是否存在交集(包括边界和内部)
  • touches(a, b):判断两个多边形仅在边界相交,无公共内部点
  • 组合使用 not a.touches(b) and a.intersects(b) 即可满足你的需求:仅当存在公共内部点时返回True

代码示例

from django.contrib.gis.geos import Polygon

# 示例1:完全不相交 → 返回False
poly_a = Polygon(((0,0), (0,1), (1,1), (1,0), (0,0)))
poly_b = Polygon(((2,2), (2,3), (3,3), (3,2), (2,2)))
print(not poly_a.touches(poly_b) and poly_a.intersects(poly_b))  # False

# 示例2:仅边相交 → 返回False
poly_c = Polygon(((0,0), (0,2), (2,2), (2,0), (0,0)))
poly_d = Polygon(((2,0), (2,2), (3,2), (3,0), (2,0)))
print(not poly_c.touches(poly_d) and poly_c.intersects(poly_d))  # False

# 示例3:存在公共内部点 → 返回True
poly_e = Polygon(((0,0), (0,2), (2,2), (2,0), (0,0)))
poly_f = Polygon(((1,1), (1,3), (3,3), (3,1), (1,1)))
print(not poly_e.touches(poly_f) and poly_e.intersects(poly_f))  # True

# 两多边形相等 → 返回True
poly_g = Polygon(((0,0), (0,2), (2,2), (2,0), (0,0)))
poly_h = poly_g.clone()
print(not poly_g.touches(poly_h) and poly_g.intersects(poly_h))  # True

数据库查询场景

如果需要在QuerySet中过滤符合条件的多边形对象,可使用对应的查询参数:

from myapp.models import PolygonModel

target_polygon = Polygon(...)  # 你的目标多边形
# 查找与目标多边形存在公共内部点的对象
matching_polygons = PolygonModel.objects.filter(
    geom__intersects=target_polygon,
    geom__touches=False
)

内容的提问来源于stack exchange,提问作者Ernesto Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:17:04