首页 > 解决方案 > 当用户位置仅移动时,如何使用 setregion() 设置区域?

问题描述

我已经尝试删除我的 setRegion() 但它仍然不允许地图平移。该构建覆盖了用于探索地图视图的手指手势,并在恢复到原始位置之前做出了非常简短的响应。我不确定这个问题。我已经将我的代码重写为一个新项目并且没有问题,有人可以向我解释我哪里出错了吗?

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    
    let locationManager = CLLocationManager()
    let regionInMeters: Double = 15000
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        checkLocationServices()
    }

    
    func setupLocationManager(){
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }
    
    func centerUserLocation(){
        if let location = locationManager.location?.coordinate{
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
            mapView.setRegion(region, animated: true)
        }
    }

    func checkLocationServices(){
        if CLLocationManager.locationServicesEnabled(){
            setupLocationManager()
            checkLocationAuthorization()
        } else {
            // alert user must turn on
        }
    }
    
    func checkLocationAuthorization(){
        switch CLLocationManager.authorizationStatus(){
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            centerUserLocation()
            locationManager.startUpdatingLocation()
            break
        case .denied:
            mapView.showsUserLocation = false
            break
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            break
        case .restricted:
            //supervisory controls enabled
            mapView.showsUserLocation = false
            break
        case .authorizedAlways:
            mapView.showsUserLocation = true
            break
        }
    }
    
}

extension ViewController: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else {return}
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)
    }
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()
    }
}

标签: iosswiftiphonexcode

解决方案


您正在呼入- 这将setRegiondidUpdateLocations您每次获得位置更新时更改地图区域;大约每秒一次,best准确;即使用户没有移动

如果您希望在地图视图上跟踪用户,您应该使用内置userTrackingMode功能。


推荐阅读