0

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

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

2 回答 2

3

您的扩展适用于CLLocationCoordinate2D.

为了让它工作,你需要在一个实例中调用它,所以:

改变:

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

为了

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

注意后面的括号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)
        }
于 2016-02-09T19:20:47.463 回答
0

我假设您正在尝试计算从当前位置到 (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.

于 2016-02-09T19:22:17.750 回答