簡體   English   中英

計算兩個long / lat之間的距離

[英]Calculate distance between two long/lat

在研究了很多而沒有找到解決方案之后我不得不問。 如何計算Mysql中兩個長/點之間的距離? (有效的方式?)

我也找到了這個解決方案,但在那里我不知道哪個是@lat @long而且我沒有使用Points因為spring-data-jpa不允許使用Geometry Type(除了使用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

在MySQL 5.7.x中,最有效的方法是使用幾何函數:

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

你會得到米的距離。

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

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

對於那些也在搜索此類代碼的人,以下代碼計算給定點與表格行中坐標之間的距離。 其中48.306... is the given latitude的數字48.306... is the given latitude ,而14.28... is the given longitude的數字14.28... is the given longitude

距離以km為單位計算,數字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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM