美文网首页
Swift 定位和地图小Demo

Swift 定位和地图小Demo

作者: 金天动地 | 来源:发表于2019-06-12 23:50 被阅读0次

1.导入头文件

import CoreLocation
import MapKit

2.遵守CLLocationManageDelegate代理,注意引用住CLLocationManager,在viewDidLoad中设置,位置管理者代理,显示经度,请求授权等相关信息

class ViewController: UIViewController, CLLocationManagerDelegate {
    private let locationManager = CLLocationManager()
    private var previousPoint: CLLocation?
    private var totalMovementDistance = CLLocationDistance(0)
    
    @IBOutlet var latitudeLabel: UILabel!
    @IBOutlet var longitudeLabel: UILabel!
    @IBOutlet var horizontalAccuracyLabel: UILabel!
    @IBOutlet var altitudeLabel: UILabel!
    @IBOutlet var verticalAccuracyLabel: UILabel!
    @IBOutlet var distanceTraveledLabel: UILabel!
    @IBOutlet var mapView:MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
    }

3.不要急着进行定位,可以通过代理方法授权状态改变调用

func locationManager(_ manager: CLLocationManager,
                    didChangeAuthorization status: CLAuthorizationStatus) {
        print("Authorization status changed to \(status.rawValue)")
        switch status {
        case .authorizedAlways, .authorizedWhenInUse:
            locationManager.startUpdatingLocation()
            mapView.showsUserLocation = true
        default:
            locationManager.stopUpdatingLocation()
            mapView.showsUserLocation = false
        }
    }
  1. 通过代理方法设置成功的回调和失败的回调
func locationManager(_ manager: CLLocationManager,
                   didFailWithError error: Error) {
        let errorType = error._code == CLError.denied.rawValue
                        ? "Access Denied": "Error \(error._code)"
        let alertController = UIAlertController(title: "Location Manager Error",
                                message: errorType, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .cancel,
                                handler: { action in })
        alertController.addAction(okAction)
// 可以添加app,直接打开设置,进行设置
        present(alertController, animated: true,
                                completion: nil)
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations
                            locations: [CLLocation]) {
        if let newLocation = locations.last {
            // %g  =>(科学技术法)\u{00B0} => 度的单位
            let latitudeString = String(format: "%g\u{00B0}",
                            newLocation.coordinate.latitude)
            latitudeLabel.text = latitudeString
            
            let longitudeString = String(format: "%g\u{00B0}",
                            newLocation.coordinate.longitude)
            longitudeLabel.text = longitudeString
            
            let horizontalAccuracyString = String(format:"%gm",
                            newLocation.horizontalAccuracy)
            horizontalAccuracyLabel.text = horizontalAccuracyString
            
            let altitudeString = String(format:"%gm", newLocation.altitude)
            altitudeLabel.text = altitudeString
            
            let verticalAccuracyString = String(format:"%gm",
                            newLocation.verticalAccuracy)
            verticalAccuracyLabel.text = verticalAccuracyString
            
            if newLocation.horizontalAccuracy < 0 {
                // invalid accuracy
                return
            }
            
            
            if newLocation.horizontalAccuracy > 100 ||
                    newLocation.verticalAccuracy > 50 {
                // accuracy radius is so large, we don't want to use it
                return
            }
            
            if previousPoint == nil {
                totalMovementDistance = 0
                let start = Place(title:"Start Point",
                                        subtitle:"This is where we started",
                                        coordinate:newLocation.coordinate)
                mapView.addAnnotation(start)
                let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate,
                                        100, 100)
                mapView.setRegion(region, animated: true)
            } else {
                print("movement distance: " +
                    "\(newLocation.distance(from: previousPoint!))")
                totalMovementDistance +=
                    newLocation.distance(from: previousPoint!)
            }
            previousPoint = newLocation
            
            let distanceString = String(format:"%gm", totalMovementDistance)
            distanceTraveledLabel.text = distanceString
        }
    }

5.要添加大头针,其实就是添加大头针模型,创建一个类继承NSObject,然后倒入MapKit,继承MKAnnotation,点击MKAnnotation拷贝其属性,创建一个初始化方法.

import UIKit
import MapKit

class Place: NSObject, MKAnnotation {
    let title: String?
    let subtitle: String?
    var coordinate: CLLocationCoordinate2D
    
    init(title:String, subtitle:String, coordinate:CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}

6.结果如下: 拷贝稍微修改就可以玩了.


WechatIMG32.jpeg

相关文章

网友评论

      本文标题:Swift 定位和地图小Demo

      本文链接:https://www.haomeiwen.com/subject/mccdfctx.html