Several years ago I wrote smth similar, I used GoggleMaps, look through the code, maybe it will be helpful, I really don't remember what are all that numbers in angle counting
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))
}
}
And this is the func which do the rotation, you can use it as soon as you receive new coordinates, or call it in for loop if you have certain polyline
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()
}