用于矩形内部或外部用户的Javascript解决方案

Javascript solution for user being inside or outside a rectangle

本文关键字:用户 Javascript 解决方案 外部 内部 用于      更新时间:2023-09-26

我检查了Stackoverflow和许多其他页面,以找到一个Javascript(或JQuery)解决方案,该解决方案告诉我用户(其当前GPS位置)是在地图上的预定义矩形内部还是外部。圆形和正方形有很多解决方案,但我找不到矩形的解决方案。此外,矩形不得平行于赤道。它可以有任何可能的角度。进行内部/外部计算需要矩形的哪个参数?有人知道解决这个问题的Javascript解决方案吗?

要知道一个点是否在二维平面图中的矩形内,您需要:

  • 矩形的一个点的位置:X0,Y0
  • 矩形与水平轴的夹角:a
  • 所述第一边的长度:L1
  • 第二边的长度为L2

请参见此图纸。

当:时,点(X,Y)在矩形内

  • 0>=(X-X0)*cos(a)-(Y-Y0)*sin(a)>=L1
  • 0>=(X-X0)*sin(a)+(Y-Y0)*cos(a)>=L2

或者在javascript:中

function isInRectangle(x, y, x0, y0, a, l1, l2) {
    var v1 = (x-x0)*Math.cos(a) - (y-y0)*Math.sin(a);
    var v2 = (x-x0)*Math.sin(a) + (y-y0)*Math.cos(a);
    return v1 >= 0 && v1 <= l1 && v2 >= 0 && v2 <= l2;
}

使用它:

var p = {x: /*user longitude*/, y: /*user latitude*/};
var p0 = {x: /*rect longitude*/, y: /*rect latitude*/};
var a = /*angle of the rect in rad*/;
var l1 = /*length of one side of the rectangle*/
var l2 = /*length of the second size*/
isInRectangle(p.x, p.y, p0.x, p0.y, a, l1, l2); // => return true if inside, false otherwise