猿问

计算 Array 中点之间的距离并返回它们之间小于 5km 的点的数组

给定一个经纬度数组 [(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5)...] 其中 x 是纬度,y 是经度 I想要返回一个数组,它们之间的距离小于 5KM。例如,返回的数组将是 (x2,y2),(x3,y3) 这意味着这些点之间的距离小于 5km。我正在使用 Haversine 算法来计算两点之间的距离。Haversine.distance(x1,y1,x2,y2).我如何在java中实现这个?


这是我试过的,


 public static class  Point{

        private final double latitude;

        private final double longitude;

    }




Point p1 = new Point(53.594952,-1.291583);

        Point p2 = new Point(53.383100,-1.179820);

        Point p3 = new Point(53.594952,-1.179120);

        Point p4 = new Point(53.594952,-1.279120);

        Point p5 = new Point(53.594952,-1.479120);

        Point p6 = new Point(53.594952,-1.339120);


Point[] points = {p1, p2, p3, p4, p5, p6};

        Point[] nearPoints = new Point[points.length];


for (int i = 0; i <= points.length - 1; i++) {

    if (Haversine.distance(points[i].latitude, points[i].longitude, points[i + 1].latitude, points[i + 1].longitude) < 5) {

        nearPoints[i] = points[i];

    }

}


慕森卡
浏览 176回答 1
1回答

噜噜哒

假设最终结果是一个包含所有点集的数据结构Point[] p = [new Point(x1,y1), new Point(x2,y2),...];List<Point[]> closePoints = new ArrayList<Point[]>();for (int i=0; i<p.length-1; i++) {&nbsp; for (int j=i+1; j<p.length; j++) {&nbsp; &nbsp; if (Haversine.distance(p[i].latitude, p[i].longitude, p[j].latitude, p[j].longitude) < 5) {&nbsp; &nbsp; &nbsp; //Elements are inserted into the list as two-element arrays&nbsp; &nbsp; &nbsp; Point[] toAdd = {p[i], p[j]};&nbsp; &nbsp; &nbsp; closePoints.add(toAdd);&nbsp; &nbsp; }&nbsp; }}System.out.println(closePoints.get(0)[0].latitude); //access example编辑:使数据结构包含两元素数组中的点对,而不是一个接一个地存储
随时随地看视频慕课网APP

相关分类

Java
我要回答