谷歌地图当前位置Swift

时间:2017-03-17 20:52:18

标签: swift google-maps

我正在尝试使用用户当前位置呈现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()
        } 
    }
}

1 个答案:

答案 0 :(得分: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