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.locationCLLocationManager によって検出された最後の場所です。requestWhenInUseAuthorization()アプリがCLLocationManager を呼び出さrequestLocation()ず、位置情報を取得したstartUpdatingLocation()場合startMonitoringSignificantLocationChanges()、このプロパティ (および計算された距離) は になりますnil

于 2016-02-09T19:22:17.750 に答える