定位相信对于好多app都很有用处,下面来讲解下在Swift3下GPS定位的实现,相对于之前的:
1.首先导入我们需要的类
import MapKit 地图视图库
import SnapKit 这个是布局库
import CoreLocation 定位GPS相关
2.viewDidLoad 实现map的init、locationManager的delegate、全局设置locationManager
var mapView: MKMapView?
//1. create locationManager
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "我的位置"
//2.1 地图init
mapView = MKMapView.init()
self.view.addSubview(mapView!)
mapView?.snp.makeConstraints({ (make) in
make.edges.equalTo(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
})
// 2. setup locationManager
locationManager.delegate = self
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// 3. setup mapView
mapView?.delegate = self
mapView?.showsUserLocation = true
mapView?.userTrackingMode = .follow
// 4. setup test data
setupData()
// Do any additional setup after loading the view.
}
3.设置在地图上插大头针
func setupData() {
// 1. check if system can monitor regions
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// 2. region data
let title = "Lorrenzillo' s"
let coordinate = CLLocationCoordinate2DMake(31.18467660, 121.45164569)
let regionRadius = 300.0
// 3. setup region
// let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude,longitude: coordinate.longitude), radius: regionRadius, identifier: title)
// 4. setup annotation
let restaurantAnnotation = MKPointAnnotation()
restaurantAnnotation.coordinate = coordinate;
restaurantAnnotation.title = "\(title)";
self.mapView?.addAnnotation(restaurantAnnotation)
// 5. setup circle
let circle = MKCircle(center: coordinate, radius: regionRadius)
self.mapView?.add(circle)
}
else {
print("System can't track regions")
}
}
4.设置MKMapView的delegate
// draw circle 绘制范围
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.red
circleRenderer.lineWidth = 1.0
return circleRenderer
}
5.设置locationManager的delegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// updateRegions()
let currLocation: CLLocation!
currLocation = locations.last! as CLLocation
self.reverseGeocode(sender: currLocation, currLocation:currLocation)
}
6.根据经纬度获取具体位置
//解析编译地理位置
func reverseGeocode(sender: AnyObject, currLocation:CLLocation) {
let geocoder = CLGeocoder()
var p:CLPlacemark?
geocoder.reverseGeocodeLocation(currLocation, completionHandler: { (placemarks, error) -> Void in
if error != nil {
print("reverse geodcode fail: \(error!.localizedDescription)")
return
}
let pm = placemarks! as [CLPlacemark]
if (pm.count > 0){
p = placemarks![0]
// let arrayforProvince:Array = (p?.name!.componentsSeparatedByString("省"))!
guard p != nil
else {
return
}
let arrayforProvince:[String] = (p!.name?.components(separatedBy:"省"))!
let city:String = arrayforProvince.last!
let arrayforcity:[String] = (city.components(separatedBy:("市")))
self.title = arrayforcity.first;
}else{
print("No Placemarks!")
}
})
}
7.还要设置下viewDidAppear判断CLLocationManager的状态
override func viewDidAppear(_ animated: Bool) {
// 1. status is not determined
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestAlwaysAuthorization()
}
// 2. authorization were denied
else if CLLocationManager.authorizationStatus() == .denied {
//showAlert("Location services were previously denied, please enable loaction services")
}
// 3. we do have authorization
else if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}