import UIKit
import MapKit
class ViewController: UIViewController,MKMapViewDelegate {
var selectedAnnotion : MKAnnotation!
override func viewDidLoad() {
super.viewDidLoad()
//初始化地图
let map = MKMapView.init(frame: self.view.bounds)
map.delegate = self
//设置地图类型
map.mapType = .standard
//初始化一个地理坐标
let coordinate2D = CLLocationCoordinate2D.init(latitude: 39.01123, longitude: 116.222525)
//初始化一个地址区域并设置缩放比例
let region = MKCoordinateRegion.init(center: coordinate2D, span: .init(latitudeDelta: 0.2, longitudeDelta: 0.2))
//设置地图的显示区域
map.setRegion(region, animated: true)
//初始化一个标注点对象
let objcAnnotation = MKPointAnnotation()
//设置标注点地理坐标
objcAnnotation.coordinate = coordinate2D
//设置标注点对象的标题文字
objcAnnotation.title = "家"
//设置标注点对象的子标题文字
objcAnnotation.subtitle = "大家"
//将标注点添加到地图视图
map.addAnnotation(objcAnnotation)
self.view.addSubview(map)
}
//用来设置返回的标注视图
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "annoteationView"
//从地图视图中,获取一个具有相同标识符的,并且可被复用的标注视图
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
//如果没有可被复用的标注视图,则初始化一个新的标注视图
if annotationView == nil {
annotationView = MKAnnotationView.init(annotation: annotation, reuseIdentifier: identifier)
}
//初始化一个信息类型的按钮控件,当用户点击的时候弹出提示框
let button = UIButton.init(type: .infoDark)
button.addTarget(self, action: #selector(showInfo), for: .touchUpInside)
//设置标注视图的左侧的附加视图为控制视图为该控制对象
annotationView?.leftCalloutAccessoryView = button
annotationView?.image = UIImage.init(named: "地图")
//设置处于焦点状态的标注地图
self.selectedAnnotion = annotation
//允许标注视图弹出气泡,以显示额外的信息
annotationView?.canShowCallout = true
return annotationView
}
@objc func showInfo(sender : UIButton) {
let message = "弹出的内容就是这个"
let alter = UIAlertController.init(title: "内容提示", message: message, preferredStyle: .alert)
let alterOK = UIAlertAction.init(title: "OK", style: .default, handler: nil)
alter.addAction(alterOK)
self.present(alter, animated: true, completion: nil)
}
//监控标注视图被添加到地图视图中的事件
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
print("打印每个视图的标题"+((view.annotation?.title)!)!)
}
}
//用来监听标注视图选择的状态时的事件
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
//获取坐标
print(view.annotation?.coordinate as Any)
//获取标题
print(view.annotation?.title as Any)
//获取副标题
print(view.annotation?.subtitle as Any)
}
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
print("地理区域将要开始变化")
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
print("地理区域变化结束调用")
}
func mapViewWillStartLoadingMap(_ mapView: MKMapView) {
print("地图即将加载")
}
func mapViewWillStartRenderingMap(_ mapView: MKMapView) {
print("地图视图即将开始渲染地图信息调用此方法")
}
func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
print("地图视图完成加载调用此方法")
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
print("地图视图完成地图信息的渲染时调用此法")
}
}