1. 程式人生 > >Java計算兩個經緯度間的距離最簡單的方式

Java計算兩個經緯度間的距離最簡單的方式

開發中經常會遇到計算兩個點(經緯度)之間的距離或者計算最近門店的場景,下面簡單實現一下如何計算兩個經緯度之間相隔的距離。

1、匯入geodesy的maven依賴 或者到阿里雲maven倉庫下載jar包

<dependency>
  <groupId>org.gavaghan</groupId>
  <artifactId>geodesy</artifactId>
  <version>1.1.3</version>
</dependency>

 

2、實現計算

package
com.test.gps; import org.gavaghan.geodesy.Ellipsoid; import org.gavaghan.geodesy.GeodeticCalculator; import org.gavaghan.geodesy.GeodeticCurve; import org.gavaghan.geodesy.GlobalCoordinates; public class CaculateDistanceTest { public static void main(String[] args) { GlobalCoordinates source
= new GlobalCoordinates(29.490295, 106.486654); GlobalCoordinates target = new GlobalCoordinates(29.615467, 106.581515); double meter = getDistanceMeter(source, target); System.out.println(meter + "米"); } public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo) {
//選擇合適座標系,歐洲之外選擇WGS84座標系 Ellipsoid ellipsoid; if (!isPointInEurope(gpsFrom) && !isPointInEurope(gpsTo)) { ellipsoid = Ellipsoid.WGS84; } else { ellipsoid = Ellipsoid.GRS80; } //建立GeodeticCalculator,傳入座標系、經緯度用於計算距離 GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo); return geoCurve.getEllipsoidalDistance(); } public static boolean isPointInEurope(GlobalCoordinates point) { try { double northernmostPoint = dms2Decimal(new int[]{ 81, 48, 24 }); double southernmostPoint = dms2Decimal(new int[]{ 34, 48, 2 }); double westernmostPoint = dms2Decimal(new int[]{ -24, 32, 3 }); double easternmostPoint = dms2Decimal(new int[]{ 69, 2, 0 }); return northernmostPoint > point.getLatitude() && southernmostPoint < point.getLatitude() && westernmostPoint < point .getLongitude() && easternmostPoint > point.getLongitude(); } catch (RuntimeException e) { throw new RuntimeException(e); } } public static double dms2Decimal(int[] dms) throws RuntimeException { if (dms != null && dms.length == 3) { int sign = dms[0] > 0 ? 1 : -1; double decimal = 0.0D; decimal += (double) Math.abs(dms[0]); double secondsTotal = (double) (dms[1] * 60 + dms[2]); decimal += secondsTotal / 3600.0D; return truncateDecimal(decimal) * (double) sign; } else { throw new RuntimeException(); } } public static double truncateDecimal(double decimal) { double factor = Math.pow(10.0D, 6.0D); return Math.rint(decimal * factor) / factor; } }

3、輸出結果:

對比百度地圖的結果,存在幾十米的誤差,對於一般應用場景可以滿足。