iOS中可以簡單地使用MapKit框架來進行地圖的相關開發工作.
import UIKit
import MapKit
class 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.
在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時候執行一些操作, 如自動放到或縮小.
// 呈現該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中心, 指定范圍的一片區域.
除此之外, 下一篇准備學習高德地圖的相關開發.