Google 地图未显示当前位置或定位按钮

Google Maps not showing current location or locate button

我将 google 地图视图嵌入到 TabBar 控制器中,它是选项卡中的第二项。视图加载地图但不显示当前位置或定位按钮。我已经编辑了方案以包含供构建使用的位置。

    var locationManager = CLLocationManager()
    var didFindMyLocation = false

    override func viewDidLoad() {
        super.viewDidLoad()

        var camera = GMSCameraPosition.cameraWithLatitude(33.7,
            longitude: -77.4, zoom: 8.0)
        mapView.camera = camera

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)

        // Do any additional setup after loading the view.
    }

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == CLAuthorizationStatus.AuthorizedWhenInUse {
            mapView.myLocationEnabled = true
        }
    }

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : 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
        }
    }

如果之前设置了位置权限 func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) 可能不会被调用,因为授权状态没有改变。

您也可以只手动执行授权检查,然后在地图上启用该位置

if CLLocationManager.locationServicesEnabled()
                && CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse {
   mapView.myLocationEnabled = true
}

Checking authorization status documentation