swift3 - 获取设备位置和取地址-当然也有借鉴

首先是真机调试,模拟器不行,其次请添加两个位置获取权限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 =

            [NSForegroundColorAttributeNameUIColor(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)

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值