如何在Swift中设置初始地图位置?

时间:2016-08-20 18:06:28

标签: ios swift google-maps google-maps-sdk-ios

我正在尝试将地图上的初始位置设置为我从存储在数据库中的用户配置文件中获得的坐标,例如userLocation。我在GMSCameraPosition中拨打viewDidLoad,但注意到模拟器检测到当前位置并将地图置于其中心而不是我想要设置的位置。我可以看到地图位于userLocation上,但会立即移动到当前位置。

我甚至调用stopUpdatingLocation方法但没有成功。

stopUpdatingLocation在停止之前调用位置更新一次吗?当我使用断点进行追踪时,这就是我的看法!

GMSCameraPosition是否也会更改基础坐标或只关注提供的坐标?

以下是代码。

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.distanceFilter = 50
    locationManager.requestWhenInUseAuthorization()

    mapView.delegate = self

    if userLocation != nil {

        mapView.myLocationEnabled = false
        locationManager.stopUpdatingLocation()

        mapView.camera = GMSCameraPosition(target: selectedCoordinate!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
    } 

}

extension MapViewController: CLLocationManagerDelegate {

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedWhenInUse {

            locationManager.startUpdatingLocation()

            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }

    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()
        }

    }

}

extension MapViewController: GMSMapViewDelegate {

    func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) {

        reverseGeocodeCoordinate(position.target)

    }
}

由于

1 个答案:

答案 0 :(得分:1)

添加: -

locationManager. stopMonitoringSignificantLocationChanges()

之后

locationManager.stopUpdatingLocation()

还要注意CLLocationManagerDelegate是一个asynchronously运行类协议,这意味着一旦执行第mapView.delegate = self行,您就已将您的代理初始化为self,该代理将发送一个获取usersCurrentLocation geoCoordinates,这意味着它将检查它的协议是否在该特定类中符合委托方法,因为如果它们是,那么它将调用这些方法而不管你是否调用stopUpdatingLocation()

解决方案: -

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

   if userLocation != nil {



    locationManager.stopUpdatingLocation()


    mapView.camera = GMSCameraPosition(target: selectedCoordinate!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
} else if let location = locations.first {

         mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

         locationManager.stopUpdatingLocation()
   }

}