Created
November 20, 2020 12:54
-
-
Save Hadevs/cb7cb0de0436adb1c0634588acb0d90f to your computer and use it in GitHub Desktop.
This file contains 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
import CoreLocation | |
struct LocationUtils { | |
let isGps: Bool | |
let accuracy: Double | |
let speed: Double | |
let latitude: Double | |
let longitude: Double | |
let previousValidLatitude: Double | |
let previousValidLongitude: Double | |
let period: Double | |
static let maxSpeed = 9.0 | |
static let maxAcurracy = 100.0 | |
func getNewValidCoordinates() -> CLLocationCoordinate2D? { | |
var isValidNew: Bool = false | |
if isValidEarthCoordinates() && isNotZero() { | |
let distance = getDistanceBetween() | |
if isGps { | |
if calculateSpeed(length: distance) > LocationUtils.maxSpeed { | |
isValidNew = false | |
} else if speed > LocationUtils.maxSpeed { | |
isValidNew = false | |
} else { | |
isValidNew = true | |
} | |
} else { | |
if accuracy > LocationUtils.maxAcurracy { | |
isValidNew = false | |
} else if distance > accuracy && calculateSpeed(length: distance - accuracy) > LocationUtils.maxSpeed{ | |
isValidNew = false | |
} else { | |
isValidNew = true | |
} | |
} | |
} | |
if isValidNew { | |
if isGps { | |
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) | |
} else { | |
return CLLocationCoordinate2D(latitude: previousValidLatitude, longitude: previousValidLongitude) | |
} | |
} else { | |
return nil | |
} | |
} | |
private func isValidEarthCoordinates() -> Bool { | |
return latitude > -90.0 && latitude < 90.0 && longitude > -180.0 && longitude < 180.0 | |
} | |
private func isNotZero() -> Bool { | |
return latitude != 0.0 && longitude != 0.0 | |
} | |
private func getDistanceBetween() -> Double { | |
let lat1 = (Double.pi / 180) * latitude | |
let lon1 = (Double.pi / 180) * longitude | |
let lat2 = (Double.pi / 180) * previousValidLatitude | |
let lon2 = (Double.pi / 180) * previousValidLongitude | |
let distance = 2 * asin(sqrt(pow(sin(lat1 - lat2) / 2, 2)) + (cos(lat1) * cos(lat2) * pow(sin((lon1 - lon2) / 2), 2))) | |
return distance * 6371.0 | |
} | |
private func calculateSpeed(length: Double) -> Double { | |
return (length * 1000) / period / 1000 * 3.6 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment