Java计算两点间经纬度距离(两种方式)
生活随笔
收集整理的這篇文章主要介紹了
Java计算两点间经纬度距离(两种方式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
反余弦計算方式:
private static final double EARTH_RADIUS = 6371000; // 平均半徑,單位:m;不是赤道半徑。赤道為6378左右 public static double getDistance(Double lat1,Double lng1,Double lat2,Double lng2) {// 經緯度(角度)轉弧度。弧度用作參數,以調用Math.cos和Math.sindouble radiansAX = Math.toRadians(lng1); // A經弧度double radiansAY = Math.toRadians(lat1); // A緯弧度double radiansBX = Math.toRadians(lng2); // B經弧度double radiansBY = Math.toRadians(lat2); // B緯弧度// 公式中“cosβ1cosβ2cos(α1-α2)+sinβ1sinβ2”的部分,得到∠AOB的cos值double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)+ Math.sin(radiansAY) * Math.sin(radiansBY); // System.out.println("cos = " + cos); // 值域[-1,1]double acos = Math.acos(cos); // 反余弦值 // System.out.println("acos = " + acos); // 值域[0,π] // System.out.println("∠AOB = " + Math.toDegrees(acos)); // 球心角 值域[0,180]return EARTH_RADIUS * acos; // 最終結果}利用第三方jar包計算:
引依賴:
<!--用于計算兩點之間的距離--><dependency><groupId>org.gavaghan</groupId><artifactId>geodesy</artifactId><version>1.1.3</version></dependency>代碼:
public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){//創建GeodeticCalculator,調用計算方法,傳入坐標系、經緯度用于計算距離GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);return geoCurve.getEllipsoidalDistance();}計算結果對比:
public static void main(String[] args) {//121.717594,31.12055 121.817629,31.090867// double distance = getDistance(31.12055, 121.717594,31.090867, 121.817629);double distance = getDistance(29.090295, 106.486654,29.615467, 106.581515);System.out.println("距離" + distance + "米");GlobalCoordinates source = new GlobalCoordinates(29.090295, 106.486654);GlobalCoordinates target = new GlobalCoordinates(29.615467, 106.581515);double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);System.out.println("Sphere坐標系計算結果:"+meter1 + "米");System.out.println("WGS84坐標系計算結果:"+meter2 + "米");}總結
以上是生活随笔為你收集整理的Java计算两点间经纬度距离(两种方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Data ElasticS
- 下一篇: mysql多表统计查询示例