首先是真机调试,模拟器不行,其次请添加两个位置获取权限Privacy - Location Always Usage Description和Privacy - Location When In Use Usage Description
添加两个组件MapKit和CoreLocation
import UIKit
import MapKit
import CoreLocation
class FirstViewController2:UIViewController ,CLLocationManagerDelegate{
var locationManager :CLLocationManager!
var currLocation :CLLocation!
lazyvar mapView:MKMapView = {
let mapView =MKMapView(frame:UIScreen.main.bounds)
//用户位置追踪(用户位置追踪用于标记用户当前位置,此时会调用定位服务)
mapView.userTrackingMode = .followWithHeading
//地图的显示风格,此处设置使用标准地图
mapView.mapType = .standard
//地图是否可滚动,默认为true
mapView.isScrollEnabled =true
//地图是否缩放,默认为true
mapView.isZoomEnabled =true
//是否显示用户当前位置 ios8之后才有,默认为false
mapView.showsUserLocation =true
//为MKMapView设置delegate
//mapView.delegate = self
if#available(iOS9.0, *) {
mapView.showsCompass =true//显示指南针
mapView.showsScale =true//显示比例尺
mapView.showsTraffic =true//显示交通
}
mapView.showsBuildings =true
mapView.showsUserLocation =true
return mapView
}()
overridefunc viewDidLoad() {
view.backgroundColor =UIColor.white
//初始化位置管理器
locationManager =CLLocationManager()
locationManager.delegate =self
//设备使用电池供电时最高的精度
locationManager.desiredAccuracy =kCLLocationAccuracyBest
//精确到1000米,距离过滤器,定义了设备移动后获得位置信息的最小距离
locationManager.distanceFilter =kCLLocationAccuracyKilometer
if#available(iOS8.0, *) {
//如果是IOS8及以上版本需调用这个方法
locationManager.requestAlwaysAuthorization()
//使用应用程序期间允许访问位置数据
locationManager.requestWhenInUseAuthorization();
//启动定位
locationManager.startUpdatingLocation()
}
view.addSubview(self.mapView)
}
//FIXME: CoreLocationManagerDelegate中获取到位置信息的处理函数
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocation = locations[locations.count-1]asCLLocation
currLocation = location
if (location.horizontalAccuracy >0) {
self.locationManager.stopUpdatingLocation()
//print("wgs84坐标系 纬度: \(location.coordinate.latitude)经度: \(location.coordinate.longitude)")
self.locationManager.stopUpdatingLocation()
//print("结束定位")
}
//坐标转换成地址
let geocoder =CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Voidin
if(error ==nil)//成功
{
let array = placemark!asNSArray
let mark = array.firstObjectas!CLPlacemark
let FormattedAddressLines:NSString = ((mark.addressDictionary!asNSDictionary).value(forKey:"FormattedAddressLines")asAnyObject).firstObjectas!NSString
print(FormattedAddressLines)
} else {
print(error!)//获取位置信息失败
}
}
}
//FIXME: 获取位置信息失败
func locationManager(_ manager:CLLocationManager, didFailWithError error:Error) {
print(error)
}
overridefunc viewWillAppear(_ animated:Bool) {
super.viewWillAppear(animated)
//创建左边按钮
let leftBtn =UIBarButtonItem(title:"< 返回", style: .plain, target: self, action:#selector(chartViewController.btnBack(_:)))
self.title ="定位地图"
self.navigationItem.leftBarButtonItem = leftBtn
self.navigationItem.leftBarButtonItem?.tintColor = UIColor(colorLiteralRed:255/255, green:255/255, blue:255/255, alpha:1)
self.navigationController?.navigationBar.barTintColor =
UIColor(red:0/255, green:166/255, blue:124/255, alpha:1)
self.navigationController?.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName: UIColor(colorLiteralRed:255/255, green:255/255, blue:255/255, alpha:1)]
//创建左边保存按钮
let item=UIBarButtonItem(title:"保存", style:UIBarButtonItemStyle.plain, target:self, action:#selector(threeViewController.tapped2))
self.navigationItem.rightBarButtonItem = item
self.navigationItem.rightBarButtonItem?.tintColor = UIColor(colorLiteralRed:255/255, green:255/255, blue:255/255, alpha:1)
}
func btnBack(_ sender:UIButton) {
self.presentingViewController!.dismiss(animated:true, completion:nil)
}
}