使用MapKit的步驟:
1.Storyboard 中拖入 MKMapView(創建 Outlet 連接)
2.在 .swift
文件的開頭 import MapKit
3.在類的后面寫上:MKMapViewDelegate
這之后就可以開始使用 MapKit 啦~
與地圖有關的常用代碼
世界地圖那么大,我們在用地圖控件的時候,其實一般都只會讓地圖顯示用戶附近的地圖圖像,或者顯示某個具體坐標點附近的圖像,一般不會上來就出現世界大地圖的情況。
下面的代碼是 讓地圖控件顯示某個區域的地圖圖像 的方法:
@IBOutlet var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
//緯度
let latitude:CLLocationDegrees = 43.095181
//經度
let longitude:CLLocationDegrees = -79.006424
//緯度范圍
let latDelta:CLLocationDegrees = 0.05
//經度范圍
let lonDelta:CLLocationDegrees = 0.05
//擴展區域的比例
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
//確定地點
let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
//確定區域
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
//讓地圖顯示確定好的區域
map.setRegion(region, animated: false)
}
貌似好難記住啊~其實有訣竅:只要記住 setRegion
這個方法就好啦~
在你敲入 setRegion
時,發現這個方法需要你提供一個參數,然后你再去創建這個參數,創建這個參數的使用,還需要另外的參數,這樣依次往后推,你需要的所有的數據就能創建好了。