【问题标题】:SWIFT: How to make an app zoom to your current location on launching?SWIFT:如何让应用程序在启动时缩放到您当前的位置?
【发布时间】:2016-12-13 16:41:56
【问题描述】:

我正在尝试构建一个应用程序,当您打开它时它会缩放到您当前的位置。以下是我目前的代码。

class MapVC: UIViewController {

@IBOutlet weak var mapView: MKMapView!

let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.requestAlwaysAuthorization()
    mapView.zoomToUserLocation()
}
}

extension MKMapView {
func zoomToUserLocation() {
    print(userLocation.location?.coordinate)
    guard let coordinate = userLocation.location?.coordinate else { return }
    let region = MKCoordinateRegionMakeWithDistance(coordinate, 10000, 10000)
    setRegion(region, animated: true)
}      
}

此代码不能解决问题。我相信这是因为应用程序在收到位置授权后没有时间获取用户位置。我正在寻找一个函数来等待应用程序有一个位置,然后调用 zoomToUserLocation 函数。我已经用一个不起作用的do-while循环尝试了这个。我可以设置延迟,但这意味着缩放是在特定时间完成的,而我希望尽快完成缩放。我在目标 C 中找到了解决方案,但无法翻译。

【问题讨论】:

    标签: swift xcode mapkit cllocationmanager


    【解决方案1】:

    这种方法可能会有所帮助setUserTrackingMode(_:animated:),但我认为这不是您想要的。

    最适合您的解决方案是在CLLocationManager 的委托上实现locationManager(_:didChangeAuthorization:)locationManager(_:didUpdateLocations:)。然后你在didUpdateLocations中调用zoomToUserLocation()

    另一个观察结果是,您不应该在viewDidLoad() 内为地图设置动画,因为它还没有出现在屏幕上。这应该在viewDidAppead() 中完成。

    【讨论】:

    • 嘿,我在 didChangeAuthorization 和 didUpdateLocations 中都调用了它,虽然它们在开始时都被称为 write,但当前用户位置的值都是 nil。
    【解决方案2】:

    您需要一个跨度和一个区域...跨度允许您设置要放大多远...

    let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
            if let center = location?.coordinate {
                let region = MKCoordinateRegion(center: center, span: span)
    
                self.mapView.setRegion(region, animated: true)
                self.mapView.showsUserLocation = true
    

    【讨论】:

      猜你喜欢
      • 2012-03-15
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多