我正在检查 Stackoverflow 和许多其他页面,以找到一个 Javascript(或 JQuery)解决方案,它可以告诉我用户(及其当前 GPS 位置)是否位于 map 上预定义矩形的内部或外部。圆形和正方形有很多解决方案,但我找不到矩形的解决方案。 此外,矩形不得与 f.e 平行。赤道。它可以有任何可能的 Angular 。 进行内部/外部计算需要矩形的哪些参数?有人知道解决这个问题的 Javascript 解决方案吗?
最佳答案
要知道一个点是否在 2D 平面图中的矩形内部,您需要:
- 矩形中一点的位置:X0,Y0;
- 矩形与水平轴的 Angular :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
关于用户在矩形内部或外部的Javascript解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570939/