如何检测某个点是否在圆圈中?

时间:2013-01-30 07:05:26

标签: javascript google-maps google-maps-api-3

如何测试LatLng点是否在圆的范围内? (Google Maps JavaScript v3)

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

6 个答案:

答案 0 :(得分:14)

使用spherical geometry library(请务必将其与API一起提供)

function pointInCircle(point, radius, center)
{
    return (google.maps.geometry.spherical.computeDistanceBetween(point, center) <= radius)
}

答案 1 :(得分:2)

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

(x1 - x2)^2 + (y1 - y2)^2 <= D^2 

答案 2 :(得分:1)

您可以使用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));

答案 3 :(得分:0)

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

var isInside=Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) >= r*r;

答案 4 :(得分: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;
}

答案 5 :(得分: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/fencery