Java - 从位置集合中获取基于距离的位置

时间:2014-10-30 11:37:55

标签: gps

我有一组具有Longitude和lattitude作为属性的对象。现在我想得到所有那些距离为50英里半径的输入经度和纬度的物体。我应该使用什么数据结构和搜索所有这些点的算法。

1 个答案:

答案 0 :(得分:0)

借助以下代码来解决我的问题。

    package com.csc.banking.celeriti.cache.srv.utils;

    public class GeoDistanceCalculator {


        private static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
          if (unit == 'K') {
            dist = dist * 1.609344;
          } else if (unit == 'N') {
            dist = dist * 0.8684;
            }
          return (dist);
        }


        public static double distanceKms(double lat1, double lon1, double lat2, double lon2){
            return distance(lat1, lon1, lat2, lon2, 'K');
        }

        public static double distanceNauticalMiles(double lat1, double lon1, double lat2, double lon2){
            return distance(lat1, lon1, lat2, lon2, 'N');
        }

        public static double distanceMiles(double lat1, double lon1, double lat2, double lon2){
            return distance(lat1, lon1, lat2, lon2, 'M');
        }

        private static double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }

        private static double rad2deg(double rad) {
          return (rad * 180 / Math.PI);
        }

        public static void main(String[] args) {
            System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') + " Miles\n");
            System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'K') + " Kilometers\n");
            System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'N') + " Nautical Miles\n");

            System.out.println(distance(28.6207641, 77.36392920000003, 28.6314512, 77.21666720000007, 'K') + " Connaught Place Delhi to Noida 62\n");


        }

    }