我是编程新手。 我发现了下面的代码,它除了中心位置以外都做了一切(放大地图,蓝色点全部工作)。 如果我在模拟器(城市运行)中运行,蓝色点就会从页面运行。如何使“地图上的中心位置”工作?
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager!.delegate = self
map.showsUserLocation = true
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager!.startUpdatingLocation()
} else {
locationManager!.requestWhenInUseAuthorization()
}
}
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
locationManager!.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
map.setRegion(coordinateRegion, animated: true)
locationManager?.stopUpdatingLocation()
locationManager = nil
}
}
为什么不在地图视图中使用'userTrackingMode'属性? – xoudini
谢谢Xoudini我是编程新手,对userTrackingMode一无所知,所以我不知道如何使用它。 – Doug
当位置服务处于打开状态时,'yourMapView.userTrackingMode = .follow'自动使用户居中,请参阅[documentation](https://developer.apple.com/reference/mapkit/mkmapview/1616208-usertrackingmode)。 – xoudini