2017-09-19 164 views
0

經過很多研究並沒有達成解決方案之後,我不得不問。 如何計算Mysql中兩個長/緯度點之間的距離? (有效的方式?)計算兩個長/經緯度之間的距離

我還發現this的解決方案,但我不知道這@lat @long是,我沒有使用點,因爲彈簧數據的JPA犯規允許幾何類型(除了使用MysqlSpatial方言)

在Java中我正在計算是這樣的:

private double getDistanceFromLatLonInKm(double lat1,double lon1,double lat2,double lon2) { 
    int R = 6371; //Earth Radius 
    double dLat = degreeToRadiant(lat2-lat1); 
    double dLon = degreeToRadiant(lon2-lon1); 
    double a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) + 
        Math.cos(degreeToRadiant(lat1)) * Math.cos(degreeToRadiant(lat2)) * 
          Math.sin(dLon/2) * Math.sin(dLon/2) 
      ; 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    return R * c; //Distance in km 
} 

而我的表/實體包含了經度緯度一列,另一個。

另一個問題,有沒有可能解決這個問題,如前所述與春季數據jpa?

我試着將Java代碼翻譯成Mysql,但距離很遠。

SELECT name, (6371 * (
    2 * ATAN2(
       SQRT(
        SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) + 
        COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((48.3069400-longitude)/2)) * 
        SIN(RADIANS((48.3069400-longitude)/2)) 
       ),SQRT(
        1-(SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) + 
        COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((48.3069400-longitude)/2)) * 
        SIN(RADIANS((48.3069400-longitude)/2))) 
       ) 
      ) 
)) as distance FROM event 
+0

可能出現[找到兩個緯度/長點之間距離的最快方法](https://stackoverflow.com/questions/1006654/fastest-way-to-find-distance-between-two-lat-long-點) –

+0

我已經鏈接到第三句話...... –

+0

@ MarkusG.what是你的MySQL版本嗎? – olegsv

回答

1

在MySQL 5.7.x的最有效的方法恕我直言是使用幾何函數:

SELECT st_distance_sphere(POINT(lat1, long1) , POINT(lat2, long2)); 

你會得到米的距離。

在MariaDB上,st_distance(...)將返回相似的結果。

+0

不適用於10.1.19-MariaDB –

+0

事實上,[兼容性矩陣](https://mariadb.com/kb/en/library/mysqlmariadb-spatial-support-matrix/)表示MariaDB不支持距離函數。 – olegsv

+0

@MarkusG。使用ST_DISTANCE() – olegsv

0

好吧,我找到了解決辦法,並在我上面的代碼中的錯誤,我忘了插入經度哈哈

對於那些誰也尋找這樣的代碼,下面的代碼計算之間的距離給定點和表格中的座標。 其中48.306... is the given latitude和數字與14.28... is the given longitude

該距離計算公里和數字6371是地球半徑。

SELECT name, (6371 * (
    2 * ATAN2(
       SQRT(
        SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) + 
        COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((14.2858300-longitude)/2)) * 
        SIN(RADIANS((14.2858300-longitude)/2)) 
       ),SQRT(
        1-(SIN(RADIANS((48.3069400-latitude))/2) * SIN(RADIANS((48.3069400-latitude)/2)) + 
        COS(RADIANS(latitude)) * COS(RADIANS(48.3069400)) * SIN(RADIANS((14.2858300-longitude)/2)) * 
        SIN(RADIANS((14.2858300-longitude)/2))) 
       ) 
      ) 
)) as distance FROM event 
相關問題