【发布时间】:2016-12-14 09:47:40
【问题描述】:
我对编码有点陌生,并提出了这个问题。我正在制作基于 MapKit 的垃圾箱查找器应用程序,我想在地图上显示从用户位置到我的图钉的距离。我已经制作了将 CLLocationCoordinate2D 转换为 CLLocation 的函数,并具有显示从一个点到另一个点的距离的函数,但我似乎无法在 locationmanager 函数中使用用户位置。
这是我的代码:
@IBOutlet weak var mapView: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
}
func distancePointToPoint(location1: CLLocationCoordinate2D, location2: CLLocationCoordinate2D) -> String {
let cllocation1 = converter(location: location1)
let cllocation2 = converter(location: location2)
let distance = cllocation1.distance(from: cllocation2)
let shortDistance = distance - distance.truncatingRemainder(dividingBy: 0.1) //makes sure there is only one number behind comma
if shortDistance < 0 {
return "The distance is \(shortDistance) meters"
}
else {
return "The distance is \(shortDistance - (shortDistance / 1000).truncatingRemainder(dividingBy: 0.1)) kilometers"
}
}
所以我需要在 distancePointToPoint 函数中使用用户位置作为 location1。
我知道使用任何其他函数我都可以返回值,但我没有任何值可以提供 locationmanager 函数,因为它将从设备本身获取它。
我已经进行了研究,我发现的唯一其他方法是将 myLocation 变量放在函数之外,并且只更改函数内部的值,但是 xcode 开始抱怨该类没有初始化程序并且我不知道该怎么办。
抱歉,我刚开始学习代码时犯了任何愚蠢的错误。
感谢任何帮助!
【问题讨论】:
-
您可以在 didupdatelocation 之外添加用户位置注释,首先您需要在 userdefault 中存储当前位置的纬度和经度,然后在函数之外访问它,这样您就可以管理它只有一次
-
感谢您的回答!你能解释一下我需要做什么吗?正如我所说,我在这方面几乎是一个完整的新手,除了纯婴儿代码谈话之外什么都不懂????
-
解决了您的问题吗?
-
它可能会,但我需要更深入地研究在 userdefaults 中存储数据,因为我还没有任何经验。
-
让我告诉你实现它的确切方法等待2分钟,我正在回答你的问题
标签: swift3 core-location distance cllocationmanager