标签:mapkit
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 1 | annotation 2 |
---|---|
有时候, 我们希望地图出现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中心, 指定范围的一片区域.
除此之外, 下一篇准备学习高德地图的相关开发.
标签:mapkit
原文地址:http://blog.csdn.net/icetime17/article/details/45251755