创建大头针、增加标记及覆盖物
步骤-SB拖入地图视图-然后如下
import MapKit
class MapViewController: UIViewController,MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
//创建大头针
let center = CLLocationCoordinate2DMake(23.114155, 113.318977)
let span = MKCoordinateSpanMake(0.2, 0.2)
self.mapView.region = MKCoordinateRegionMake(center, span)
//向地址增加标记
let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = "当前大约位置"
annotation.subtitle = ""
self.mapView.addAnnotation(annotation)
//创建一个新的圆形覆盖物
let overlay = MKCircle(centerCoordinate: center, radius: 5000)
self.mapView.addOverlay(overlay)
}
//自定义大头针样式,默认是红色
//func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
//覆盖物的委托方法
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 0.5)
circleRenderer.fillColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 0.5)
return circleRenderer
}
}
当前位置实时显示
import MapKit
class MapViewController: UIViewController,MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var spanState = true
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
self.mapView.showsUserLocation = true
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
let coord = userLocation.coordinate
let center = CLLocationCoordinate2DMake(coord.latitude, coord.longitude)
print(center)
if spanState == true { //首次时候的缩放范围
let span = MKCoordinateSpanMake(0.01, 0.01)
self.mapView.region = MKCoordinateRegionMake(center, span)
spanState = !spanState
}
}
}