Search code examples
swiftcllocationcoordinate2d

Using CoreLocation2d


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)

Solution

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