MapKit --- iOS中的地圖架構
iOS中可以簡單地使用MapKit架構來進行地圖的相關開發工作.
基本步驟:import MapKit ViewController 繼承 MKMapViewDelegate 協議 添加一個MapKit View 準備一個相應的region資訊, 即以哪為中心, 方圓多少範圍 在mapView中設定該region即可 添加地理位置的標註annotation 地理位置標註添加到map中的相應操作.ViewController
import UIKitimport MapKitclass ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mapView.delegate = self // MKMapView中有一個delegate屬性, ViewController繼承MKMapViewDelegate協議, 就必須實現該協議中的必需的方法 let location = CLLocationCoordinate2D(latitude: 22.284681, longitude: 114.158177) let span = MKCoordinateSpanMake(0.05, 0.05) // region可以視為以location為中心, 方圓多少範圍 let region = MKCoordinateRegion(center: location, span: span) // mapView會顯示該region的map // mapView.mapType = MKMapType.Standard mapView.setRegion(region, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
ViewController如上所示, 只需準備好location, 然後只需mapView的setRegion操作即可呈現map.
地理位置標註annotation
在map中, 我們可以在指定的位置添加一個標註annotation.
// 在地圖上添加一個位置標註 let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Hong Kong" annotation.subtitle = "Someplace" mapView.addAnnotation(annotation) // 在地圖上添加另一個位置標註 let location2 = CLLocationCoordinate2D(latitude: 22.294681, longitude: 114.170177) let annotation2: MKPointAnnotation = MKPointAnnotation() annotation2.coordinate = location2 annotation2.title = "Hong Kong" annotation2.subtitle = "Someplace2" mapView.addAnnotation(annotation2)
效果:
annotation 1 |
annotation 2 |
|
|
annotation顯示時的操作
有時候, 我們希望地圖出現annotation時候執行一些操作, 如自動放到或縮小.
// 呈現該annotation的時候, 調用該方法 func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) { println("didAddAnnotationViews") let annotationView: MKAnnotationView = views[0] as! MKAnnotationView let annotation = annotationView.annotation let region: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 500, 500) self.mapView.centerCoordinate = region.center self.mapView.setRegion(region, animated: true) self.mapView.selectAnnotation(annotation, animated: true) }}
如: 該annotation一旦在map中呈現, 則自動跳轉到以該region的center為map中心, 指定範圍的一片地區.
除此之外, 下一篇準備學習高德地圖的相關開發.