Using CoreLocation2d

74 Views Asked by At

Im trying to get the distance from my current location to some location but it not printing the location. Im not sure if I use it the extension right.

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

}

The output is like this:

distance = (Function)
2

There are 2 best solutions below

0
On BEST ANSWER

Your extension is suited for an instance of 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.

If you want to keep this line exactly like it is, then the changes in your extension will be like this:

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

I'm assuming you're trying to compute the distance from your current location to (10.30, 44.34). This is done by using:

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

locationManager.location is the last location detected by the CLLocationManager. If your app didn't requestWhenInUseAuthorization() and call CLLocationManager requestLocation(), startUpdatingLocation() or startMonitoringSignificantLocationChanges() and obtained a location fix, this property (and the computed distance) would be nil.