【问题标题】:Calculating distance using latitude longitude coordinates in kilometers with Spark 2 Scala使用 Spark 2 Scala 使用纬度经度坐标以公里为单位计算距离
【发布时间】:2019-12-19 04:03:01
【问题描述】:

我正在尝试使用 Scala 2.11.8 中 Spark 2.3 中的半正弦公式计算两个地理坐标之间的距离(以公里为单位)。

我想计算两个动作之间的用户距离:

我有经度和纬度,这个想法是以公里为单位的距离。

+-----------+------------------+------------------+-----------------+
|       user| distance         |Longitude_Centroid|Latitude_Centroid|    
+-----------+------------------+------------------+-----------------+    
|-2525      |              null| 7.038245640847997|39.48919886182785|    
|-2147      |12818.567585128396| 7.038245640847997|39.48919886182785|
|-2147      |12818.567585128396| 7.038245640847997|39.48919886182785|    
|-2525      |12862.278795753988| 7.050538333095536|39.49362379246508|

使用 Python DataFrame 对我来说效果很好,但是我在 Scala Spark 中苦苦挣扎!

我使用了下面的代码,但似乎不能正常工作。

df4.withColumn("a", pow(sin(( lag($"Latitude_Centroid", 1).over(window) - 
$"Latitude_Centroid") / 2), 2) + cos(($"Latitude_Centroid")) * 
cos((lag($"Latitude_Centroid", 1).over(window)) * 
pow(sin((lag($"Longitude_Centroid", 1).over(window) - 
$"Longitude_Centroid") / 2), 2))).withColumn("distance", atan2(sqrt($"a"), 
sqrt(-$"a" + 1)) * 2 * 6371).select("imei","distance","Longitude_Centroid","Latitude_Centroid").show(50)

【问题讨论】:

    标签: scala apache-spark haversine


    【解决方案1】:

    刚刚找到解决办法

    df4.withColumn("lat_lag", lag($"Latitude_Centroid",     1).over(window)).withColumn("lng_lag", lag($"Longitude_Centroid",  1).over(window)).select("imei","lat_lag","lng_lag","date_from","Longitude_Centroid","Latitude_Centroid")  .withColumn("a", pow(sin(toRadians($"Latitude_Centroid" - $"lat_lag") / 2), 2) + cos(toRadians($"lat_lag")) * cos(toRadians($"Latitude_Centroid")) * pow(sin(toRadians($"Longitude_Centroid" - $"lng_lag") / 2), 2))  .withColumn("distance", atan2(sqrt($"a"), sqrt(-$"a" + 1)) * 2 * 6371)   .select("imei","lat_lag","lng_lag","date_from","Longitude_Centroid","Latitude_Centroid","distance")  .show()
    

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2014-12-16
      • 1970-01-01
      • 2021-05-10
      • 2016-02-03
      • 2015-10-18
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      相关资源
      最近更新 更多