我有點新來編碼,並提出了這個問題。我即將製作基於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中,然後在功能之外對其進行存取,這樣,您將只能對其進行一次管理 –
謝謝爲您的答案!你能解釋一下我需要做什麼嗎?正如我所說,我幾乎是一個完全在這方面的菜鳥,並不明白比純嬰兒代碼談話 –
它解決了你的問題? –