2015-08-29 211 views
0

我有我的谷歌地图视图嵌入在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 
     } 
    } 

回答

2

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

您也可以手动只授权进行检查,然后在地图

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

Checking authorization status documentation

+0

我怎样才能从该点用户位置上启用的位置?我在viewdidload中实现了上面的内容,并在if语句块中添加了:mapView.camera = GMSCameraPosition.cameraWithTarget(mapView.myLocation.coordinate,zoom:10.0),但程序崩溃,因为mapView.myLocation.coordinate为零。 – wxcoder

+0

@wxcoder地图视图在可用时从核心位置异步检索当前,因此它不会立即可用。与你原来的例子中的位置将被检索到更新observeValueForKeyPath中的相机,一切都应该没问题。 – makeshiftJake

相关问题