iOS 內建的 MapKit 框架就能完成大部分基礎地圖需求,不必一開始就引入第三方服務。
MKMapViewDelegate 協定。setRegion:animated:。import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self // 遵循 MKMapViewDelegate 協定後設定 delegate
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.mapType = MKMapType.standard
mapView.setRegion(region, animated: true)
}
}
準備好 location,再對 mapView 做一次 setRegion,地圖就出來了。
// 第一個標注 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() annotation2.coordinate = location2 annotation2.title = "Hong Kong" annotation2.subtitle = "Someplace2" mapView.addAnnotation(annotation2)
| annotation 1 | annotation 2 |
|---|---|
![]() |
![]() |
有時我們希望標注一被加進地圖,畫面就自動縮放到那個位置:
// 呈現該 annotation 時呼叫
func mapView(_ mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) {
println("didAddAnnotationViews")
let annotationView: MKAnnotationView = views[0]
let annotation = annotationView.annotation
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 500, 500)
self.mapView.centerCoordinate = region.center
self.mapView.setRegion(region, animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
}
如此一來,標注一顯示,畫面就跳到以它為中心、方圓 500 公尺的區域並自動選中。

MapKit 還能做路線規劃、使用者定位、地圖樣式切換等事,但上面這幾個步驟已經足夠應付「顯示一個位置並標記起來」這類最常見的需求。