Skip to content

Instantly share code, notes, and snippets.

@XCarbone
Created June 25, 2018 14:16
Show Gist options
  • Save XCarbone/0a9cb31844977fb1da34d529b61db02f to your computer and use it in GitHub Desktop.
Save XCarbone/0a9cb31844977fb1da34d529b61db02f to your computer and use it in GitHub Desktop.
class FiveLastPoints {
var fiveLastPointsLocation : [CLLocationCoordinate2D] = []
var fiveLastPointsTime : [Int] = []
var totalDistance : Double = 0.0
var totalTime : Int = 0
func addNewPoint(newPoint : CLLocationCoordinate2D, time: Int) {
//first add 5 points
fiveLastPointsLocation.append(newPoint)
fiveLastPointsTime.append(time)
if (fiveLastPointsTime.count > 5) {
fiveLastPointsLocation.remove(at: 0)
fiveLastPointsTime.remove(at: 0)
}
}
func isPointValid(newPoint : CLLocationCoordinate2D, time: Int, numberOfIgnoredPoints : Int) -> Bool {
let distance = getDistanceBetweenTwoPoints(pointOne: newPoint, pointTwo: fiveLastPointsLocation.last!) * 100000
let timeDifference = Double(time - fiveLastPointsTime.last!)
if distance > ((getAverageSpeed() * timeDifference) * Double(numberOfIgnoredPoints)) + 10 {
return false
}
return true
}
func getAverageSpeed() -> Double {
calculateTotalTime()
calculateTotalDistance()
let speed = totalDistance / Double(totalTime)
return speed
}
private func calculateTotalTime() {
if !fiveLastPointsTime.isEmpty {
totalTime = fiveLastPointsTime.last! - fiveLastPointsTime.first!
}
}
private func calculateTotalDistance() {
var totalDistance = 0.0
if fiveLastPointsLocation.count > 2 {
for (index, location) in fiveLastPointsLocation.enumerated() {
if index < fiveLastPointsLocation.count - 1 {
totalDistance += getDistanceBetweenTwoPoints(pointOne: location, pointTwo: fiveLastPointsLocation[index + 1])
}
}
}
self.totalDistance = totalDistance * 100000
}
private func getDistanceBetweenTwoPoints(pointOne: CLLocationCoordinate2D, pointTwo: CLLocationCoordinate2D) -> Double {
let differenceLatitudes = Double(pointOne.latitude - pointTwo.latitude)
let differencelongitudes = Double(pointOne.longitude - pointTwo.longitude)
let distanceBetweenPoint = sqrt(pow((differenceLatitudes), 2) + pow((differencelongitudes), 2))
return distanceBetweenPoint
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment