如何找到2个变量中存在的2个纬度之间的距离

时间:2019-05-31 06:08:05

标签: scala

我正在尝试从2个变量计算2纬度之间的距离,并检查它们是否低于临界值,然后是0值,否则为1

val loc1 = Array("12.764,76.833","12.763,76.839","12.762,76.832")
val loc2 = Array("12.764,76.836")

val cut_off = Array(10)

val R = 6372.8  //Earth radius in km

def getHaversineDistance(p1Lat: Double, p1Long: Double, p2Lat: Double, p2Long: Double): Double = {
    val dLat=(p2Lat - p1Lat).toRadians
    val dLon=(p2Long - p1Long).toRadians
    val a = pow(sin(dLat/2),2) + pow(sin(dLon/2),2) * cos(p1Lat.toRadians) * cos(p2Lat.toRadians)
    R * 2 * asin(sqrt(a))
}

这里loc1包含不同的位置lat和lng。loc2​​是应与loc1的所有lat和lng进行比较并与截止值进行比较的纬度。

1 个答案:

答案 0 :(得分:0)

此代码有效,但您应该在解析器上添加一些错误检查

import Math._

val loc1 = Array("12.764,76.833", "12.763,76.839", "12.762,76.832")
val loc2 = Array("12.764,76.836")

val cut_off = Array(10)

val R = 6372.8 //Earth radius in km

def getHaversineDistance(p1Lat: Double, p1Long: Double,p2Lat: Double, p2Long: Double): Double = {
  val dLat = (p2Lat - p1Lat).toRadians
  val dLon = (p2Long - p1Long).toRadians
  val a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(p1Lat.toRadians) * cos(
  p2Lat.toRadians)
  R * 2 * asin(sqrt(a))
}

def toList(arr: Array[String]): Seq[(Double, Double)] =
  arr.map(x => (x.split(",")(0).toDouble, x.split(",")(1).toDouble)).toList

val res = for {
  l1 <- toList(loc1)
  l2 <- toList(loc2)
} yield getHaversineDistance(l1._1, l1._2, l2._1, l2._2)

 println(res) // List(0.32543327331680283, 0.34391646279701354, 0.48761200638246516)