一、配置
1、导包
import MapKit
2、View和Controller
在Main Storyboard中添加一个 MapKit View,并在Controller中添加outlet。
完成之后代码如下:
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
...
}
二、使用
1、定位
CLLocationCoordinate2D,MKCoordinateSpan,MKCoordinateRegion
三者均为简单的结构体。
// 设置定位的经纬度。
var coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
// 设置定位的精度。
var span = MKCoordinateSpan(latitudeDelta: , longitudeDelta: )
// 由 经纬度 和 精度 组成的定位区域。
var region = MKCoordinateRegion(center: coordinate, span: span)
// 在地图上显示定位区域。
mapView.setRegion(region, animated: true)
2、大头针
MKPointAnnotation
// 华南农业大学西园:+23.1614184494, +113.3474275024
var coordinate = CLLocationCoordinate2D(latitude: , longitude: )
// 实例化,以及设置。
var point = MKPointAnnotation()
point.coordinate = coordinate
point.title = "华南农业大学"
point.subtitle = "西园"
// 添加到地图。
mapView.addAnnotation(annotation)
三、结果
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiN5gDN1MjMwATMzcDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)