Swift - GMSMarker 在 GMSPath(Google Maps SDK for iOS)的 CLCoor



所有在 Google 地图中对坐标之间的标记移动进行动画处理的尝试都指向在 Swift 中使用以下代码片段:

CATransaction.begin()
CATransaction.setAnimationDuration(duration)
marker.position = coordindates
CATransaction.commit()

举个例子,这里有得票最多的SO帖子: 如何沿目标 c 中的坐标平滑移动 GMSMarker

在源坐标和目标坐标对之间进行动画处理时,这工作正常。 但是,我希望从 GMSPath 中的起始坐标到结束坐标进行动画处理。 循环访问路径中的点时,唯一显示的动画位于最后两个坐标之间。 标记仅出现在倒数第二个点处,并动画到最后一个点。

这是我的视图控制器代码。 它接收路由的一段作为编码路径(为了测试,第一个编码路径:"ika~Exi|vN|AaDzAyCTc@N[lBeEvB_ExBkExBmEjBwDXo@"(。

该代码正在遍历 GMSPath 对象内存储的所有坐标,并尝试使用上面发布的代码片段进行动画处理。 如前所述,它只显示最后两点之间的动画。

我尝试将所有代码集放在ViewDidLoad,ViewDidAppear和ViewWillAppear中。 ViewDidLoad 将缩放级别保持在洲际。 ViewDidAppear和ViewWillAppear适当地带来了放大,并导致了本文中提到的动画问题。 代码目前在 ViewDidSeem 和 ViewWillAppear 之间拆分,但如果仅放置在任一方法中,则操作相同。

import UIKit
import GoogleMaps
import CoreLocation
class MapVC:UIViewController {
var mapView:GMSMapView?
var polyline:GMSPolyline?
var path:GMSPath?
var encodedPath:String? = nil
var marker:GMSMarker?
override func viewDidLoad() {
super.viewDidLoad()

setupMap()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if encodedPath != nil {
self.path = GMSPath(fromEncodedPath: encodedPath!)
self.polyline = GMSPolyline(path: path)
self.polyline!.map = self.mapView!
let bounds:GMSCoordinateBounds = GMSCoordinateBounds(path: path!)
let update = GMSCameraUpdate.fit(bounds, withPadding: 10.0)
self.mapView!.animate(with: update)

} else {
print("nil path")
}
let a=2
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
var index:UInt = 0
let count:UInt = self.path!.count()
if count > 0 {
marker = GMSMarker(position: self.path!.coordinate(at:index))
marker!.map = self.mapView
index += 1
while index < count {
CATransaction.begin()
CATransaction.setAnimationDuration(30)
self.marker!.position = self.path!.coordinate(at:index)
CATransaction.commit()
index += 1
}
}
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupMap() {
let camera = GMSCameraPosition.camera(withLatitude: 36.5, longitude: -82.5, zoom: 16)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
}
}

使用计时器找到解决方案:https://github.com/antonyraphel/ARCarMovement/blob/master/ARCarMovementSwift/ARCarMovementSwift/ViewController.swift

来自视图控制器的更新代码如上所示:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
marker = GMSMarker(position: self.path!.coordinate(at:self.index))
marker!.map = self.mapView
timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: 
#selector(MapVC.timerTriggered), userInfo: nil, repeats: true)

}

@objc func timerTriggered() {
if self.index < self.path!.count() {
CATransaction.begin()
CATransaction.setAnimationDuration(1.9)
self.marker!.position = self.path!.coordinate(at:index)
CATransaction.commit()
self.index += 1
} else {
timer.invalidate()
timer = nil
}
}

最新更新