【发布时间】:2017-02-14 17:55:08
【问题描述】:
我是编程新手。 我找到了下面的代码,它除了中心位置之外什么都做。(放大、地图、蓝点都可以。) 如果我在模拟器中运行,(城市运行)蓝点就会跑出页面。
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 我是编程新手,对 userTrackingMode 一无所知,所以我不知道如何使用它。
-
yourMapView.userTrackingMode = .follow在定位服务开启时自动将用户居中,参见documentation。
标签: ios swift core-location