如何找到坐标之间的距离?

82

我希望可以展示两个CLLocation坐标之间的距离。是否有一种不需要使用复杂数学公式的方法来实现呢?如果没有,你会如何使用公式来计算距离呢?


3
好的,我下次会这么做。对此我感到抱歉。 - John Doe
10个回答

242

CLLocation有一个distanceFromLocation方法,因此可以给定两个CLLocations:

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];

或者在 Swift 4 中:

//: Playground - noun: a place where people can play

import CoreLocation


let coordinate₀ = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate₁ = CLLocation(latitude: 5.0, longitude: 3.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters

您在这里得到的是距离,以为单位,因此1英里 = 1609米

if(distanceInMeters <= 1609)
 {
 // under 1 mile
 }
 else
{
 // out of 1 mile
 }

我该如何将这个转换成英里? - John Doe
5
根据谷歌的数据,一米等于0.000621371英里。因此,我建议将其乘以0.000621371。 - Glenn Howes
1
这不是真正的“路程”距离。根据苹果文档 - “此方法通过沿着地球曲率追踪连接它们的两个位置之间的距离来测量它们之间的距离。所得到的弧线是平滑的曲线,不考虑两个位置之间的具体高度变化。” https://developer.apple.com/documentation/corelocation/cllocation/1423689-distance ..因此,如果您正在寻找驾驶距离,则找到正确距离的可靠方法迄今为止一直是Google Maps Distance Matrix API或MKRoute。 - Anjan Biswas
1
@GlennHowes 是的,它确实有这个问题。很可能OP正在尝试找到两点之间的驾驶(或其他交通方式)距离,在这种情况下,仅使用由distanceFromLocation导出的地理空间距离将是完全不正确的。对于驾驶距离,正确的实现方法是使用MKRoute,它将为您提供“路线距离”distance(以米为单位),以及其他一些信息,如预计旅行时间、交通类型等-https://developer.apple.com/documentation/mapkit/mkroute - Anjan Biswas
1
正如@vijay在上面的评论中所报告的,这就是他的距离与Google地图相比不正确的原因。Google地图和MKRoute会考虑路线信息来计算实际运输距离,而简单的“distanceFromLocation”则不会,因此我建议您更新答案以澄清这一点,以避免通过Google访问此页面的人们感到困惑。 - Anjan Biswas
显示剩余8条评论

20

Swift 4.1

import CoreLocation

//My location
let myLocation = CLLocation(latitude: 59.244696, longitude: 17.813868)

//My buddy's location
let myBuddysLocation = CLLocation(latitude: 59.326354, longitude: 18.072310)

//Measuring my distance to my buddy's (in km)
let distance = myLocation.distance(from: myBuddysLocation) / 1000

//Display the result in km
print(String(format: "The distance to my buddy is %.01fkm", distance))

10

试试这个:

distanceInMeters = fromLocation.distanceFromLocation(toLocation)
distanceInMiles = distanceInMeters/1609.344

来自Apple文档

返回值:两个位置之间的距离(以米为单位)。


有没有办法将其转换为英里? - John Doe
同样来自苹果文档 - “此方法通过跟踪连接它们的两个位置之间沿地球曲率的线来测量它们之间的距离。结果弧是一个平滑的曲线,不考虑两个位置之间的具体高度变化。” https://developer.apple.com/documentation/corelocation/cllocation/1423689-distance - Anjan Biswas
很好,您使用了正确的因子“1609.344”。https://en.wikipedia.org/wiki/Mile - thetrutz
1
对于iOS 10+,通过Measurement类执行英里转换将非常有用:let miles = Measurement(value: meters, unit: UnitLength.meters).converted(to: UnitLength.miles).value - gyratory circus

7
import CoreLocation

//My location
let myLocation = CLLocation(latitude: 31.5101892, longitude: 74.3440842)

//My Next Destination
let myNextDestination = CLLocation(latitude: 33.7181584, longitude: 73.071358)

//Finding my distance to my next destination (in km)
let distance = myLocation.distance(from: myNextDestination) / 1000

3
func calculateDistanceInMiles(){

    let coordinate₀ = CLLocation(latitude:34.54545, longitude:56.64646)
    let coordinate₁ = CLLocation(latitude: 28.4646, longitude:76.65464)
    let distanceInMeters = coordinate₀.distance(from: coordinate₁)
    if(distanceInMeters <= 1609)
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"
    }
    else
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"

    }
}

4
虽然这段代码可以回答问题,但是提供关于为什么和/或如何回答问题的额外背景信息,有助于提高其长期价值。 - rollstuhlfahrer

3

针对 Swift 4

   let locationOne = CLLocation(latitude: lat, longitude: long)
   let locationTwo = CLLocation(latitude: lat,longitude: long)

  let distance = locationOne.distance(from: locationTwo) * 0.000621371

  distanceLabel.text = "\(Int(round(distance))) mi"

1

对于Objective-C:

您可以使用distanceFromLocation来查找两个坐标之间的距离。

代码片段:

CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];

CLLocationDistance distance = [loc1 distanceFromLocation:loc2];

您的输出将以米为单位显示。

这里的问题标题是“Swift”。因此,您可能需要更新您的答案或添加“对于Objective-C:”。@Vijay - Dory Daniel

1
import UIKit
import CoreLocation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var currentLocation = CLLocation(latitude: 23.1929, longitude: 72.6156)
        var DestinationLocation = CLLocation(latitude: 23.0504, longitude: 72.4991)
        var distance = currentLocation.distance(from: DestinationLocation) / 1000
        print(String(format: "The distance to my buddy is %.01fkm", distance))
    }
}

虽然这段代码可能回答了问题,但最好解释一下它是如何解决问题的,而不引入其他问题,并解释为什么要使用它。仅有代码的答案从长远来看并不实用。 - koen

1
您也可以像Android开发人员一样使用HaversineDistance算法,这对于在Android中有类似应用程序的情况非常有帮助,否则上面的答案对您是正确的。
import UIKit

func haversineDinstance(la1: Double, lo1: Double, la2: Double, lo2: Double, radius: Double = 6367444.7) -> Double {

let haversin = { (angle: Double) -> Double in
    return (1 - cos(angle))/2
}

let ahaversin = { (angle: Double) -> Double in
    return 2*asin(sqrt(angle))
}

// Converts from degrees to radians
let dToR = { (angle: Double) -> Double in
    return (angle / 360) * 2 * .pi
}

let lat1 = dToR(la1)
let lon1 = dToR(lo1)
let lat2 = dToR(la2)
let lon2 = dToR(lo2)

return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1))
}

let amsterdam = (52.3702, 4.8952)
let newYork = (40.7128, -74.0059)

// Google says it's 5857 km so our result is only off by 2km which could be due to all kinds of things, not sure how google calculates the distance or which latitude and longitude google uses to calculate the distance.
haversineDinstance(la1: amsterdam.0, lo1: amsterdam.1, la2: newYork.0, lo2: newYork.1)

我从参考链接https://github.com/raywenderlich/swift-algorithm-club/blob/master/HaversineDistance/HaversineDistance.playground/Contents.swift中选取了上述代码。


-2

Swift 5.

func calculateDistance(mobileLocationX:Double,mobileLocationY:Double,DestinationX:Double,DestinationY:Double) -> Double {

        let coordinate₀ = CLLocation(latitude: mobileLocationX, longitude: mobileLocationY)
        let coordinate₁ = CLLocation(latitude: DestinationX, longitude:  DestinationY)

        let distanceInMeters = coordinate₀.distance(from: coordinate₁)

        return distanceInMeters
    }

用于

let distance = calculateDistance("add parameters")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接