为 GMSMapView 和 CLLocationManager 等创建属性
@IBOutlet 弱 var mapView: GMSMapView!
var locationManager = CLLocationManager()
var didFindMyLocation = false
并在 viewdidload 方法中为地图视图添加观察者以进行位置更新,如下所示
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(48.857165, longitude: 2.354613, zoom: 2.0)
mapView.camera = camera
mapView.delegate = self
mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if !didFindMyLocation {
let myLocation: CLLocation = change![NSKeyValueChangeNewKey] as! CLLocation
mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 10.0)
mapView.settings.myLocationButton = true
didFindMyLocation = true
}
}
// MARK: - CLLocationManagerDelegate
extension MapViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
mapView.myLocationEnabled = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
}
didFindMyLocation 是 bool 属性,不要忘记在 Info.plist 文件中添加 'NSLocationWhenInUseUsageDescription' 键