使用apple內建的MapKit,做一個移動紀錄
首先要先加入CoreLocation的Framework,提供地理位置、經緯度、海拔等
導入Framework : CoreLocation & MapKit
加入protocol : CLLocationManagerDelegate & MKMapViewDelegate
import UIKit import CoreLocation import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {...}
創建locationManager,用於偵測用戶位置變化
設定map會顯示user當下位置並隨著user移動
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self //委派給ViewController
locationManager.desiredAccuracy = kCLLocationAccuracyBest //設定為最佳精度
locationManager.requestWhenInUseAuthorization() //user授權
locationManager.startUpdatingLocation() //開始update user位置
map.delegate = self //委派給ViewController
map.showsUserLocation = true //顯示user位置
map.userTrackingMode = .follow //隨著user移動
}
user位置授權,需要在info.plist文件中加入2個“Key”
Privacy — Location When In Use Usage Description
Privacy — Location Always and When In Use Usage Description
這2個Key會在locationManager.requestWhenInUseAuthorization()中使用到,若沒有加入Key,系統就不會受理位置的授權。
那開始獲取用戶位置時locationManager.startUpdatingLocation()需要使用locationManager(_:didUpdateLocations:)
method來做即時更新
(Main.storyboard就不另外說明了)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//An array of CLLocation
objects containing the location data.
let userLocation: CLLocation = locations[0] //最新的位置在[0]
self.latitube.text = String(userLocation.coordinate.latitude)
self.longitube.text = String(userLocation.coordinate.longitude)
self.course.text = String(userLocation.course)
self.speed.text = String(userLocation.speed)
self.altitube.text = String(userLocation.altitude)
...
經緯度轉實現地址位置,會使用到CLGeocoder(地理編碼)
CLGeocoder().reverseGeocodeLocation(userLocation) { (placemark, error) in
if error != nil {
print(error)
} else {
//the geocoder actually returns CLPlacemark objects, which contain both the coordinate and the original information that you provided.
if let placemark = placemark?[0] {
//print(placemark)
var address = ""
if placemark.subThoroughfare != nil {
address += placemark.subThoroughfare! + " "
}
if placemark.thoroughfare != nil {
address += placemark.thoroughfare! + "\n"
}
if placemark.subLocality != nil {
address += placemark.subLocality! + "\n"
}
if placemark.subAdministrativeArea != nil {
address += placemark.subAdministrativeArea! + "\n"
}
if placemark.postalCode != nil {
address += placemark.postalCode! + "\n"
}
if placemark.country != nil {
address += placemark.country!
}
self.address.text = String(address)
}
}
}