【发布时间】:2016-10-11 23:36:29
【问题描述】:
我想在用户打开应用后立即显示他们的当前位置。我使用 Mapbox iOS SDK。但它根本不起作用。我不知道怎么了。我打开后只能看到不相关的地图。
import UIKit
import Mapbox
import CoreLocation
class ViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate
{
@IBOutlet weak var mapView: MGLMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let mapView = MGLMapView(frame: view.bounds)
mapView.userTrackingMode = .Follow
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
mapView.setCenterCoordinate(center, zoomLevel: 15, animated: true)
view.addSubview(mapView)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print ("Errors:" + error.localizedDescription)
}
}
【问题讨论】:
-
您是否被提升为允许位置访问?在第一次更新后停止位置更新也是一个坏主意;第一个位置可能不太准确
-
那么我应该在什么时候停下来?我这样做是因为考虑到用户的电池寿命。
-
如果您的目标是 ios9+',您可以使用请求定位过程,当您有准确的位置时该过程将停止。如果你想,在早期版本上工作,那么你需要检查位置的horizontalAccuracy 属性,并在它足够好时停止。您在真实设备上获得的第一个位置通常是 +/- 1000m