realm / realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
https://realm.io
Apache License 2.0
16.32k stars 2.15k forks source link

Support for ordering objects by distance #2193

Open jefflopes opened 9 years ago

jefflopes commented 9 years ago

Given model objects with latitude and longitude properties, I would like to order the objects by their distance from a provided latitude and longitude.

marchyman commented 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)
}
jefflopes commented 9 years ago

@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.

jdelaune commented 9 years ago

Yes geospatial support would be great

kexoth commented 9 years ago

@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.

ricardosobral commented 8 years ago

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.