gpt4 book ai didi

swift - 使用 CoreLocation2d

转载 作者:行者123 更新时间:2023-11-28 11:10:46 25 4
gpt4 key购买 nike

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

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 的实例。

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.

如果你想保持这一行原样,那么你的扩展中的变化将是这样的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com