Last active
April 20, 2023 20:44
-
-
Save stonetip/5da546c3b4d54acdcae8888d3e0ac3b0 to your computer and use it in GitHub Desktop.
functions to use and smooth course from CLLocationManager and get north angle relative to current angle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var courseAvgX: Double = 0 | |
var courseAvgY: Double = 0 | |
func getVectorAvg(latestReading: Double) -> Double { | |
let deg2Rad = 180 / Double.pi | |
// convert reading to radians | |
var theta = latestReading / deg2Rad | |
// running average | |
courseAvgX = courseAvgX * 0.5 + cos(theta) * 0.5; | |
courseAvgY = courseAvgY * 0.5 + sin(theta) * 0.5; | |
// get the result in degrees | |
var avgAngleDeg = atan2(courseAvgY, courseAvgX) * deg2Rad; | |
// result is -180 to 180. change this to 0-360. | |
if(avgAngleDeg < 0){ avgAngleDeg = avgAngleDeg + 360} | |
return avgAngleDeg; | |
} | |
// location | |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
guard let location = locations.last else { | |
return | |
} | |
let lat = location.coordinate.latitude | |
let lon = location.coordinate.longitude | |
let alt = location.altitude | |
let course = location.course | |
currentLat = lat; | |
currentLon = lon; | |
print("location.course: \(course)" ) | |
let avgCourse = getVectorAvg(latestReading: course) | |
print("avgCourse: \(avgCourse)") | |
self.navIndicatorView.courseAngle = CGFloat(360.0 - avgCourse + course) * -1.0 | |
self.navIndicatorView.northAngle = CGFloat(360.0 - course) * -1.0 | |
// print("northAngle: \(self.navIndicatorView.northAngle)") | |
labelLatVal.text = String(format: "%.6f", lat) | |
labelLonVal.text = String(format: "%.6f", lon) | |
labelAltVal.text = String(format: "%.f", alt * GeoMath.metersToFeet) | |
labelCourseVal.text = String(format: "%.1f", course) | |
labelHeadingVal.text = String(format: "%.1f", (avgCourse)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment