我有点新来编码,并提出了这个问题。我即将制作基于MapKit的trashcanfinder应用程序,我想显示从用户位置到地图上我的针脚的距离。我已经使我的函数将CLLocationCoordinate2D转换为CLLocation,并且具有显示从一个点到另一个点的距离的功能,但我似乎无法使用locationmanager函数外的用户位置。如何使用用户位置的位置管理功能swift 3
这是我的代码:
@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"
}
}
所以我需要使用用户位置作为LOCATION1在distancePointToPoint功能。
我知道用任何其他函数,我可以只返回值,但我没有任何值给locationmanager函数,因为它会从设备本身得到它。
我已经做了研究,我发现的唯一的其他方法是将myLocation变量放在函数之外,只更改函数内部的值,但xcode开始抱怨该类没有初始化函数我不知道该怎么做。
对不起,如果我犯了一些愚蠢的错误,因为我刚刚开始学习代码。
任何帮助表示赞赏!
您可以在didupdatelocation之外添加用户位置注释,首先您需要将当前位置的纬度和长度存储在userdefault中,然后在功能之外对其进行存取,这样,您将只能对其进行一次管理 –
谢谢为您的答案!你能解释一下我需要做什么吗?正如我所说,我几乎是一个完全在这方面的菜鸟,并不明白比纯婴儿代码谈话 –
它解决了你的问题? –