Open jefflopes opened 9 years ago
In swift...
/// return distance in meters and bearing between two lat/lon pairs
/// - Parameter lat1: latitude of starting point
/// - Parameter lon1: longitude of starting point
/// - Parameter lat2: latitude of ending point
/// - Parameter lon2: longitude of ending point
/// - Returns: tuple containg distance and bearing from starting point to ending point
///
/// distance and bearing calculated using the haversine formula
public func distanceAndBearing(lat1 lat1: Double, lon1: Double,
lat2: Double, lon2: Double) -> (Double, Double) {
let lat1R = degreesToRadians(lat1)
let lon1R = degreesToRadians(lon1)
let lat2R = degreesToRadians(lat2)
let lon2R = degreesToRadians(lon2)
let deltaLat = lat2R - lat1R
let deltaLon = lon2R - lon1R
let a = sin(deltaLat/2) * sin(deltaLat/2) +
sin(deltaLon/2) * sin(deltaLon/2) * cos(lat1R) * cos(lat2R)
let distance = 2 * asin(sqrt(a)) * R
let b = atan2(sin(deltaLon) * cos(lat2R),
cos(lat1R) * sin(lat2R) - sin(lat1R) * cos(lat2R) * cos(deltaLon))
let bearing = (radiansToDegrees(b) + 360.0) % 360.0
return (distance, bearing)
}
@marchyman Thanks for the sample code. I could retrieve all the objects and sort them as you described, but my hope is that if Realm did the sorting internally, it would be more efficient in terms of model object instances. My understanding is that Realm has a mechanism similar to Core Data's faulting that doesn't fully realize model objects until you access them.
Yes geospatial support would be great
@jefflopes & @jdelaune there is a plugin which has map annotations clustering & it has sorting by distance, caching the results, etc. Take a look at it bigfish24/ABFRealmMapView.
Lat/Longs are a very special thing and probably one of the greatest use cases for Realm. I would highly suggest for Realm to support GeoQueries given CLLocations. A differentiator that would always make me choose Realm.
Given model objects with latitude and longitude properties, I would like to order the objects by their distance from a provided latitude and longitude.