0

我正在将 Mapbox iOS SDK 集成到我的应用程序中。现在我被困在我想要实现像优步应用程序这样的汽车跟踪功能的地步。

我曾经在 Google Maps SDK 中拥有该功能,但我无法使其与 Mapbox SDK 一起使用。

我正在添加MGLPointAnnotation对象以将其添加到地图上,并希望通过动画将其从 A 点移动到 B 点。

我正在使用

UIView.animate(withDuration: TimeInterval(duration), animations: {
    // Update annotation coordinate to be the destination coordinate
    point.coordinate = newCoordinate
}, completion: nil)

但是因为MGLPointAnnotation我不能改变它的图像,因为当有转弯时我想旋转图像(注释)。

如果我使用MGLAnnotationView对象,我可以改变图像,但我不能改变它的坐标,因为它是只读的。

我应该在这里做什么来实现该功能?

4

1 回答 1

0

几年前我写过类似的,我用过GoggleMaps,看看代码,也许会有帮助,我真的不记得角度计数中的那些数字是什么

    extension Double {

    var degrees: Double {
        return self * 180.0 / Double.pi
    }

}


extension CLLocationCoordinate2D {

    func angleToPosition(position : CLLocationCoordinate2D) -> CLLocationDegrees {
        let bearingRadians = atan2(Double(position.latitude - latitude), Double(position.longitude - longitude))
        var bearingDegrees = bearingRadians.degrees
        //        print("\(bearingDegrees)")
        var roundDegrees = 360.0
        if bearingDegrees < 0 {
            if bearingDegrees > -90 {
                roundDegrees = 350
            }
            if bearingDegrees < -90 && bearingDegrees > -180 {
                roundDegrees = 370
            }
            bearingDegrees += roundDegrees
            return 360 - bearingDegrees
        }
        roundDegrees = bearingDegrees < 90 ? 350 : 360
        if bearingDegrees > 90 && bearingDegrees < 180 {
            roundDegrees = 370
        }
        UserDefaults.standard.set(bearingDegrees, forKey: "bearingDegrees")
        return roundDegrees - bearingDegrees
    }

    func duration(toDestination destination: CLLocationCoordinate2D, withSpeed speed : Double) -> Double {
        let distance = GMSGeometryDistance(self, destination)
        return distance / (speed * (1000 / 3600))
    }

}

这是进行旋转的函数,您可以在收到新坐标后立即使用它,或者如果您有某些折线,则在 for 循环中调用它

func animateCarDrive(info: [String: Any]) {
    let speed = info["speed"] as? Double ?? 40 // if your car's speed is changeable
    let position = info["position"] as? CLLocationCoordinate2D // new point position
    let duration = marker.position.duration(toDestination: position, withSpeed: speed)
    marker.rotation = marker.position.angleToPosition(position: position)
    CATransaction.begin()
    CATransaction.setAnimationDuration(duration)
    marker.position = position
    CATransaction.commit()
}
于 2019-07-29T06:19:34.670 回答