使用 CoreLocation2d

Using CoreLocation2d

我正在尝试获取从我当前位置到某个位置的距离,但它没有打印该位置。我不确定我是否使用它的扩展名。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        var location = CLLocationCoordinate2D.distanceInMetersFrom(CLLocationCoordinate2D(latitude: 10.30, longitude: 44.34))

        print("distance = \(location)")
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

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)
    }

}

输出是这样的:

distance = (Function)

您的扩展适用于 CLLocationCoordinate2D.

的实例

For it to work you need to call it in an instance, so:

change:

var location = CLLocationCoordinate2D.distanceInMetersFrom(CLLocationCoordinate2D(latitude: 10.30, longitude: 44.34))

for

var location = CLLocationCoordinate2D().distanceInMetersFrom(CLLocationCoordinate2D(latitude: 10.30, longitude: 44.34))

Notice the parenthesis after CLLocationCoordinate2D.

如果你想保持这一行原样,那么你的扩展中的变化将是这样的:

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

我假设您正在尝试计算从当前位置到 (10.30, 44.34) 的距离。 这是通过使用:

let baseLocation = CLLocation(latitude: 10.30, longitude: 44.34)
let distance = locationManager.location?.distanceFromLocation(baseLocation)

locationManager.location 是 CLLocationManager 检测到的最后一个位置。如果您的应用没有 requestWhenInUseAuthorization() 并调用 CLLocationManager requestLocation()startUpdatingLocation()startMonitoringSignificantLocationChanges() 并获得位置修复,则此 属性(和计算的距离)将成为 nil.