swift5学习之旅----地图MKMapView
显示自己的位置和print自己位置的地址(需要实机测试)
需要在info.plist添加Privacy - Location When In Use Usage DescriptionPrivacy - Location When In Use Usage Description
- 整体代码
Github还没上传,先用着Dropbox(可能要翻墙),看完有收获的感谢点个赞👍,如果翻不了墙要代码可以私聊我
https://www.dropbox.com/sh/x6i69oa66xccu7j/AACIbme_sPRyFn-5rKcdZvuba?dl=0
dropbox地图工程
- 主要功能
self.mapType = .standard
self.delegate = self
//用户位置追踪
self.userTrackingMode = .followWithHeading
//显示当前位置
self.showsUserLocation = true
//显示指南针(默认显示)
// self.showsCompass = true
//显示比例尺
self.showsScale = true
//显示交通
self.showsTraffic = true
//地图是否可缩放
self.isZoomEnabled = true
//设置地图范围(越小精度越高
// let latDelta = 0.05
// let longDelta = 0.05
// let currentLocationSpan: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)
- 定义地图区域和中心坐标,大头针
//MARK: 定义地图区域和中心坐标
// let center = CLLocation (latitude: 23.112086, longitude: 113.331042)
// let center = currLocation.coordinate
// let currentRegion = MKCoordinateRegion (center: center, span: currentLocationSpan)
//设置显示区域
// self.setRegion(currentRegion, animated: true)
//MARK: 创建大头针对象
// let objectAnnotation = MKPointAnnotation()
// //设置大头针显示的位置
// objectAnnotation.coordinate = center.coordinate
// //设置点击大头针显示后的信息
// objectAnnotation.title = "广州塔"
// objectAnnotation.subtitle = "广州海心沙"
// //添加大头针
// self.addAnnotation(objectAnnotation)
location()
- 设置位置
func location(){
//最高精度
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//使用期间允许访问位置数据
locationManager.requestWhenInUseAuthorization()
//启动定位
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
- CoreLocationManagerDelegate获取位置
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last! as CLLocation
currLocation = location
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
//设置地图范围(越小精度越高(演示时为了不透露自己的地址改了0.5,最佳我觉得是0.05)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
self.setRegion(region, animated: true)
//坐标转换成地址(我显示的是中文)
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { (placemarks, error) in
if error == nil{
let array = placemarks! as NSArray
let placemark = array.firstObject as! CLPlacemark
let address = "\(placemark.thoroughfare ?? ""), \(placemark.locality ?? ""), \(placemark.subLocality ?? ""), \(placemark.administrativeArea ?? ""), \(placemark.postalCode ?? ""), \(placemark.country ?? "")"
print("地址为: \(address)")
}else{
print("这是错误\(error!)")
}
}
}
//获取位置信息失败
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("这是错误\(error)")
}