地圖資訊是手機很大量運用的資訊之一,接下來是來整理關於目前學到的MapKit View地圖的運用
首先先拉一個新的ViewController,並將MapKit View拉近去

接著在ViewController建立參數與MapKit View做對應,這邊需要注意的地方是用Map元件需要import MapKit```swift
import UIKit
import MapKit
class MapViewController: UIViewController {
@IBOutlet weak var uimap: MKMapView!//地圖元件
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| * 取得座標資訊是由一個叫要做CLLocationManager來控制的,又IOS8取得座標資訊必須先取得使用者的授權才可以,所以必須到Info.plist新增NSLocationAlwaysUsageDescription或NSLocationWhenInUseUsageDescription兩種鍵值,而前者表示不管APP在前景或背景執行都會持續取得座標資訊,而後者只有在需要時才會去取座標定位資訊,而這兩個鍵值分別對應到CLLocationManager的requestAlwaysAuthorization和requestWhenInUseAuthorization,這邊的範例已NSLocationWhenInUseUsageDescription為例 ```swift import UIKit import CoreLocation import MapKit class MapViewController: UIViewController,CLLocationManagerDelegate {
@IBOutlet weak var uimap: MKMapView!//地圖元件 var location : CLLocationManager!; //座標管理元件 override func viewDidLoad() { super.viewDidLoad();
location = CLLocationManager(); location.delegate = self; //詢問使用者是否同意給APP定位功能 location.requestWhenInUseAuthorization(); //開始接收目前位置資訊 location.startUpdatingLocation(); }
override func viewDidDisappear(animated: Bool) { //因為GPS功能很耗電,所以被敬執行時關閉定位功能 location.stopUpdatingLocation(); } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { //取得目前的座標位置 let c = locations[0] as CLLocation; //c.coordinate.latitude 目前緯度 //c.coordinate.longitude 目前經度 let nowLocation = CLLocationCoordinate2D(latitude: c.coordinate.latitude, longitude: c.coordinate.longitude); //將map中心點定在目前所在的位置 //span是地圖zoom in, zoom out的級距 let _span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.0005, longitudeDelta: 0.0005); self.uimap.setRegion(MKCoordinateRegion(center: nowLocation, span: _span), animated: true); } }
|
接著別忘了去Info.plist新增NSLocationWhenInUsageDescription
[](http://2.bp.blogspot.com/-FwRtS6qlxv0/VPUmFe5sNwI/AAAAAAAAEbI/ZBcSw4FmZKY/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-03%2B%E4%B8%8A%E5%8D%8811.09.07.png)
接著執行看看!!
詢問是否授權取得座標資訊

地圖中心點移到你目前的位置摟~
順帶一提,如果需要把使用者的位置座標顯示出來,在mapkit view設定檔將User Location打勾即可!!

如果你有實際run過這段程式應該會發現你滑動map時,它會一直彈回你目前所在的位置,原因是我們沒有指定移動多少距離才會更新座標位置,所以didUpdateLocations會一直被呼叫,也就一直被彈回你的所在位置摟,告訴app移動多少距離再更新座標資訊即可 ```swift
location.distanceFilter = CLLocationDistance(10); //表示移動10公尺再更新座標資訊