2017-03-17 117 views
0

我試圖渲染一個帶有用戶當前位置的Google地圖,但無論我做什麼,它只會呈現默認位置(歐洲地區周圍)。由於我是Swift新手,我不知道如何調試,並且想在這裏問一下我需要做什麼。谷歌地圖當前位置Swift

斯威夫特代碼

import UIKit 
import GoogleMaps 

class ViewController: UIViewController { 

    @IBOutlet weak var mapView: GMSMapView! 
    var locationManager = CLLocationManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locationManager.delegate = self 
     locationManager.requestWhenInUseAuthorization() 
    } 
} 
extension ViewController: CLLocationManagerDelegate { 

    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     if status == .authorizedWhenInUse { 
      locationManager.startUpdatingLocation() 
      mapView.isMyLocationEnabled = true 
      mapView.settings.myLocationButton = true 
     } 
    } 

    private func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     if let location = locations.first { 
      mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0) 
      locationManager.stopUpdatingLocation() 
     } 
    } 
} 
+0

您使用的是真實設備嗎?模擬器中沒有gps。 – Magnas

+0

剛剛在模擬器上運行不會呈現用戶的當前位置? – ckim16

+1

不可以。您可以使用控制檯上方的小圖標中的一個來選擇「模擬」位置,但模擬器默認爲沒有用戶位置。 – Magnas

回答

0

用做外景經理的變化autorization代表,你應該使用 開始更新位置,然後 之前委託方法刪除私鑰,並把下面的屬性在做更新位置的委託方法。刪除停止更新位置方法。

func locationManager(_ manager: CLLocationManager, 
     didChangeAuthorization status: CLAuthorizationStatus) { 
    switch status { 
    case .authorizedAlways, .authorizedWhenInUse: 
     self.locationManager.startUpdatingLocation() 
     break 

    case .denied, .restricted: 
     self.disableLocationRelatedFeatures() 
     break 

    // Do nothing otherwise. 
    default: break 
    } 
} 

    self.mapView.isMyLocationEnabled = true 
    self.mapView.settings.myLocationButton = true