distanceFromLocation - 计算两点之间的距离

Ste*_*hen 49 objective-c core-location ios

关于Core Location的一个简单问题,我正在尝试计算两点之间的距离,代码如下:

    -(void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation
    {   

    // Configure the new event with information from the location.
        CLLocationCoordinate2D newCoordinate = [newLocation coordinate];
        CLLocationCoordinate2D oldCoordinate = [oldLocation coordinate];

        CLLocationDistance kilometers = [newCoordinate distanceFromLocation:oldCoordinate] / 1000; // Error ocurring here.
        CLLocationDistance meters = [newCoordinate distanceFromLocation:oldCoordinate]; // Error ocurring here.
}
Run Code Online (Sandbox Code Playgroud)

我在最后两行收到以下错误:

错误:无法转换为指针类型

我一直在搜索谷歌,但我找不到任何东西.

dea*_*rne 114

试试这个:

CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
Run Code Online (Sandbox Code Playgroud)

您尝试使用的方法是CLLocation对象上的方法:)

  • 并且还记在我的脑海中"这种方法通过在它们之间跟踪地球曲率"苹果文件来测量两个位置之间的距离.所以这不会通过道路给出距离. (11认同)

Atu*_*ain 22

距离是在2个CLLocations之间计算的,而不是在坐标之间计算的.

您需要使用这些坐标使用以下代码行获取相应坐标的CLLocations

CLLocation *newLocation = [[CLLocation alloc] initWithCoordinate: newCoordinate altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:nil];
Run Code Online (Sandbox Code Playgroud)

类似地,对于其他坐标,您可以使用以下代码行计算这两个位置之间的距离

CLLocationDistance kilometers = [newLocation distanceFromLocation:oldLocation] / 1000;
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你.

更新: Swift 3.0

let distanceKiloMeters = (newLocation.distance(from: oldLocation))/1000
Run Code Online (Sandbox Code Playgroud)


小智 11

在斯威夫特

让我们创建一个计算两个位置之间距离的方法函数:

 func distanceBetweenTwoLocations(source:CLLocation,destination:CLLocation) -> Double{

        var distanceMeters = source.distanceFromLocation(destination)
        var distanceKM = distanceMeters / 1000
        let roundedTwoDigit = distanceKM.roundedTwoDigit
        return roundedTwoDigit

    }
Run Code Online (Sandbox Code Playgroud)

如果您只想要两位数:

extension Double{

    var roundedTwoDigit:Double{

        return Double(round(100*self)/100)

        }
    }
Run Code Online (Sandbox Code Playgroud)


Max*_*der 5

如果您要使用2个CLLocationCoordinate2D值,那么您可以使用它.

这是Xcode 7.1上的Swift 2.1

import CoreLocation

extension CLLocationCoordinate2D {

    func distanceInMetersFrom(otherCoord : CLLocationCoordinate2D) -> CLLocationDistance {
        let firstLoc = CLLocation(latitude: self.latitude, longitude: self.longitude)
        let secondLoc = CLLocation(latitude: otherCoord.latitude, longitude: otherCoord.longitude)
        return firstLoc.distanceFromLocation(secondLoc)
    }

}
Run Code Online (Sandbox Code Playgroud)