2015-08-29 264 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

相關問題