ios - 当用户位置仅移动时,如何使用 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()
}
}
解决方案
您正在呼入- 这将setRegion
在didUpdateLocations
您每次获得位置更新时更改地图区域;大约每秒一次,best
准确;即使用户没有移动
如果您希望在地图视图上跟踪用户,您应该使用内置userTrackingMode
功能。
推荐阅读
- c++ - 循环没有结束,我需要在代码中找到错误
- postgresql - 如何根据postgres中的开始和结束时间按小时划分持续时间?
- php - WooCommerce 结帐分散样式
- karate - 空手道名称不适用于嵌套功能文件调用
- linux - 带回退交换的 ram 驱动器
- user-interface - 如何选择动态 X 路径值
- arrays - 包含二进制数作为元素的打印数组中的输出不匹配
- python - 如何使用python打印多源和多目标图的所有路径
- python - Python FCM 在单击通知后转到 Android 应用程序中的特定 .xlm
- assembly - 关于arm组件PC寄存器的问题