我正在尝试将地图上的初始位置设置为我从存储在数据库中的用户配置文件中获得的坐标,例如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)
}
}
由于
答案 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()
}
}