我是一名 Swift 开发新手,我正在构建一个应用程序来跟踪 map 上城市公交车的位置。
我遇到的问题是,我希望 MKAnnotations 在 GPS 位置之间平滑移动(从旧位置到新 JSON 中的位置),而不是被删除并重新出现。
到目前为止,我的应用程序正在检索 JSON,该 JSON 被解码为遵守 MKAnnotation 协议(protocol)的对象数组。
然后我用这个方法将它们全部显示在 map 上:
func updateUI(json: MyModelClass) {
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(json.busArray)
}
每 10 秒下载一次 JSON,并触发 updateUI
方法,删除现有的 MKAnnotations 并添加新的。
如果您有任何建议,我将非常感激。
如果需要,这里是模型:
struct MyModelClass: Codable {
let busArray: [Bus]
enum CodingKeys: String, CodingKey {
case busArray = "result"
}
init(busArray: [Bus]) {
self.busArray = busArray
}
}
class Bus: NSObject, Codable, MKAnnotation {
let latitude, longitude: Double
let time, title, brigade: String?
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 52.22977, longitude: 21.01178)
enum CodingKeys: String, CodingKey {
case latitude = "Lat"
case longitude = "Lon"
case time = "Time"
case title = "Lines"
case brigade = "Brigade"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.latitude = try container.decode(Double.self, forKey: .latitude)
self.longitude = try container.decode(Double.self, forKey: .longitude)
self.title = try container.decode(String.self, forKey: .title)
self.time = try container.decode(String.self, forKey: .time)
self.brigade = try container.decode(String.self, forKey: .brigade)
self.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
最佳答案
类似这样的吗?
MKAnnotationView继承自UIView。
我通过不将annotationView添加为MapView
的注释来做到这一点。
相反,我做了类似的事情
mapView.addSubview(annotaionView)
此后,使用 iOS 的一种方法来为 UIViews
制作动画:
最简单的方法是使用 UIView.animate{ }
在上面的示例中,我使用了 UIKitdynamics
和 SnapBehaviour,请参阅 https://www.raywenderlich.com/2326-uikit-dynamics-tutorial-getting-started
您需要的一件事是将 map 坐标转换为 UIView
坐标:
var snapTo = mapView.convert(cdPOI.coordinate, toPointTo: mapView)
动画完成后,我将注释作为 subview 删除,并执行类似 mapView.addAnnotation(annotation)
关于ios - 如何使 MKAnnotations 在 map 上平滑移动(调整其坐标)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104397/