8

如何测试 LatLng 点是否在圆的范围内?(谷歌地图 JavaScript v3)

getBounds() 方法返回圆的边界框,它是一个矩形,所以如果一个点落在圆之外但在边界框内,你会得到错误的答案。

4

6 回答 6

15

使用球面几何库(确保将其包含在 API 中)

function pointInCircle(point, radius, center)
{
    return (google.maps.geometry.spherical.computeDistanceBetween(point, center) <= radius)
}
于 2013-01-30T11:42:41.527 回答
3

您可以手动进行距离比较,相当简单。

(x1 - x2)^2 + (y1 - y2)^2 <= D^2 
于 2013-01-30T07:09:25.680 回答
2

您可以使用 Circle 对象来显示它;

new google.maps.Circle({
            map : map,
            center : new google.maps.LatLng(lat,lng),
            strokeColor:'#00FFCC',
            strokeWeight:2,
            fillOpacity:0,
            radius:radiusm
        });

并将勾股定理应用于坐标:但在这种情况下,要使其成为“真实”圆,因为纬度和经度之间的 1° 之间的比率因纬度而异,您至少应该像这样调整它们:

var kmRadius = 100; //(radius of 100 km)
var lat_gap = kmRadius/111.1;
var lng_gap = lat_gap / Math.cos(lat / (Math.PI/180));
于 2013-01-30T07:24:37.957 回答
0

你为什么不简单地用勾股定理来计算呢?你知道a²+b²=c²。如果 c 低于 r(半径),你就知道它在里面。

var isInside=Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) >= r*r;
于 2013-01-30T07:11:52.553 回答
0

像这样的东西应该可以解决问题(代码未经测试):

public boolean pointInCircle(Circle c, LatLng coord) {
  Rectangle r = c.getBounds();
  double rectX = r.getX();
  double rectY = r.getY();
  double rectWidth = r.getWidth();
  double rectHeight = r.getHeight();

  double circleCenterX = rectX + rectWidth/2;
  double circleCenterY = rectY + rectHeight/2;

  double lat = coord.getLatitude();
  double lon = coord.getLongitude();

  // Point in circle if (x−h)^2 + (y−k)^2 <= r^2
  double rSquared = Math.pow(rectWidth/2, 2);
  double point = Math.pow(lat - circleCenterX, 2) + Math.pow(lon - circleCenterY, 2);

  return (point <= rSquared) ? true : false;
}
于 2013-01-30T07:27:59.250 回答
0

试试这个(Javascript):

const toRadians = (val) => {
   return val * Math.PI / 180;
}
const toDegrees = (val) => {
   return val * 180 / Math.PI;
}
// Calculate a point winthin a circle
// circle ={center:LatLong, radius: number} // in metres
const pointInsideCircle = (point, circle) => {
    let center = circle.center;
    let distance = distanceBetween(point, center);

    return distance < circle.radius; // Use '<=' if you want to get all points in the border
};

const distanceBetween = (point1, point2) => {
    var R = 6371e3; // metres
    var φ1 = toRadians(point1.latitude);
    var φ2 = toRadians(point2.latitude);
    var Δφ = toRadians(point2.latitude - point1.latitude);
    var Δλ = toRadians(point2.longitude - point1.longitude);

    var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
            Math.cos(φ1) * Math.cos(φ2) *
            Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c;
}

参考资料:http ://www.movable-type.co.uk/scripts/latlong.html

这个 npm 帮助器模块做同样的事情,并返回一个布尔值,表明该项目是否在圆圈中。

https://www.npmjs.com/package/fenery

于 2017-09-13T04:09:29.480 回答