简体   繁体   English

如何在当前位置设置MKMapView区域并跟踪用户位置?

[英]How do you set MKMapView region on current location and follow user location?

I have a button that centers the map and sets the region based on the user's current location and then sets the user tracking mode to follow. 我有一个按钮,可将地图居中并根据用户的当前位置设置区域,然后设置要遵循的用户跟踪模式。 I am following the user while moving and if they move the map or zoom out it sets the user tracking mode to none. 我在移动时关注用户,如果他们移动地图或缩小地图,则会将用户跟踪模式设置为无。

This is what I have 这就是我所拥有的

guard let currentLocation = locationManager.location else { return }
let coordinateRegion = MKCoordinateRegion(center: currentLocation.coordinate,
                                          latitudinalMeters: regionRadius,
                                          longitudinalMeters: regionRadius)
map.setRegion(coordinateRegion, animated: true)
map.setUserTrackingMode(MKUserTrackingMode.follow, animated: true)

It successfully sets the region back to the user's current location and then the user tracking mode to follow but for some reason it doesn't follow anymore. 它成功地将区域设置回用户的当前位置,然后遵循用户跟踪模式,但是由于某种原因,该模式不再遵循。

You need to wait for setRegion animation to finish so it doesn't mess with setUserTrackingMode. 您需要等待setRegion动画完成,以免与setUserTrackingMode混淆。

guard let currentLocation = locationManager.location else { return }
let coordinateRegion = MKCoordinateRegion(center: currentLocation.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)

MKMapView.animate(withDuration: 0.5, animations: {
    self.map.setRegion(coordinateRegion, animated: true)
}) { _ in
    self.map.setUserTrackingMode(MKUserTrackingMode.follow, animated: false)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM