我试图得到从我的当前位置到某个位置的距离,但它没有打印位置。我不确定我是否把它用在分机上。
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
的实例。
要使其工作,您需要在实例中调用它,因此:
更改:
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)
}
关于swift - 使用CoreLocation2d,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35299953/