我正在尝试将mapview放在用户位置的中心,但到目前为止它不起作用。我已经尝试过在运气好的物理设备上对其进行测试,但找不到有效的解决方案,请帮帮我。
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var mapView: MKMapView!
var locationManager: CLLocationManager!
let distanceSpan: Double = 500
override func viewDidLoad() {
super.viewDidLoad()
setupMapView()
}
fileprivate func setupLocationManager() {self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() == true {
if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = 1.0
locationManager.delegate = self
locationManager.startUpdatingLocation()
} else {
print("PLease turn on location services or GPS")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
self.mapView.setRegion(region, animated: true)
}
fileprivate func setupMapView() {
let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
mView.showsUserLocation = true
view.addSubview(mView)
self.mapView = mView
}