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

如何判断GPS坐标是否落在已知左下角与右上角坐标的矩形内?

判断坐标是否在矩形范围内的简洁代码

当然有!这种判断其实超级直观,用几个直白的if条件就能轻松实现,完全不需要复杂的算法。核心逻辑就是检查目标坐标的纬度和经度是否分别落在矩形的纬度区间和经度区间内。

核心思路

矩形由左下角(bottomLeft,包含纬度lat和经度lng)和右上角(topRight)定义,只要满足两个条件:

  • 目标纬度lat大于等于左下角的纬度,且小于等于右上角的纬度
  • 目标经度lng大于等于左下角的经度,且小于等于右上角的经度

目标坐标就在这个矩形范围内啦。

代码示例

伪代码(通用逻辑)

function isPointInRectangle(lat, lng, bottomLeft, topRight) {
    if (lat >= bottomLeft.lat && lat <= topRight.lat &&
        lng >= bottomLeft.lng && lng <= topRight.lng) {
        return true;
    } else {
        return false;
    }
}

Python 实现

def is_point_in_rectangle(lat, lng, bottom_left, top_right):
    # bottom_left 和 top_right 可传入字典(如 {"lat": 30.0, "lng": 110.0})或元组
    if (bottom_left["lat"] <= lat <= top_right["lat"] and
        bottom_left["lng"] <= lng <= top_right["lng"]):
        return True
    return False

JavaScript 实现

function isPointInRectangle(lat, lng, bottomLeft, topRight) {
    // bottomLeft 和 topRight 是包含 lat、lng 属性的对象
    return lat >= bottomLeft.lat && lat <= topRight.lat &&
           lng >= bottomLeft.lng && lng <= topRight.lng;
}

注意事项

  • 上面的代码适用于不跨国际日期变更线的常规矩形(也就是经度范围没有从东经跳到西经的情况)。如果你的矩形跨越了180°经线,那这个简单判断就不适用了,需要额外处理经度的循环逻辑。
  • 这里的判断是包含边界的(坐标刚好落在矩形边上也会返回true),如果需要排除边界,把>=和<=改成>和<就行。

内容的提问来源于stack exchange,提问作者Alex Kokorin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:38:58