-
Notifications
You must be signed in to change notification settings - Fork 27
/
GeoQueries.swift
310 lines (217 loc) · 11.2 KB
/
GeoQueries.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//
// GeoQueries.swift
// GeoQueries
//
// Created by mhergon on 15/10/16.
// Copyright © 2016 mhergon. All rights reserved.
//
import RealmSwift
import CoreLocation
import MapKit
enum GeoQueriesError: Error {
case invalidRealm(String)
}
// MARK: - Public extensions
public extension Realm {
/**
Find objects inside MKCoordinateRegion. Useful for use in conjunction with MapKit
- parameter type: Realm object type
- parameter region: Region that fits MapKit view
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Found objects inside MKCoordinateRegion
*/
func findInRegion<Element: Object>(type: Element.Type, region: MKCoordinateRegion, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> Results<Element> {
// Query
return try self
.objects(type)
.filterGeoBox(box: region.geoBox, latitudeKey: latitudeKey, longitudeKey: longitudeKey)
}
/**
Find objects inside GeoBox
- parameter type: Realm object type
- parameter box: GeoBox struct
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Found objects inside GeoBox
*/
func findInBox<Element: Object>(type: Element.Type, box: GeoBox, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> Results<Element> {
// Query
return try self
.objects(type)
.filterGeoBox(box: box, latitudeKey: latitudeKey, longitudeKey: longitudeKey)
}
/**
Find objects from center and distance radius
- parameter type: Realm object type
- parameter center: Center coordinate
- parameter radius: Radius in meters
- parameter order: Sort by distance (optional)
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Found objects inside radius around the center coordinate
*/
func findNearby<Element: Object>(type: Element.Type, origin center: CLLocationCoordinate2D, radius: Double, sortAscending sort: Bool?, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> [Element] {
// Query
return try self
.objects(type)
.filterGeoBox(box: center.geoBox(radius: radius), latitudeKey: latitudeKey, longitudeKey: longitudeKey)
.filterGeoRadius(center: center, radius: radius, sortAscending: sort, latitudeKey: latitudeKey, longitudeKey: longitudeKey)
}
}
public extension RealmCollection where Element: Object {
/**
Filter results from Realm query using MKCoordinateRegion
- parameter region: Region that fits MapKit view
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Filtered objects inside MKCoordinateRegion
*/
func filterGeoRegion(region: MKCoordinateRegion, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> Results<Element> {
// Realm instance pre-check
guard let _ = realm else { throw GeoQueriesError.invalidRealm("RLMRealm instance is needed to call this method") }
let box = region.geoBox
let topLeftPredicate = NSPredicate(format: "%K <= %f AND %K >= %f", latitudeKey, box.topLeft.latitude, longitudeKey, box.topLeft.longitude)
let bottomRightPredicate = NSPredicate(format: "%K >= %f AND %K <= %f", latitudeKey, box.bottomRight.latitude, longitudeKey, box.bottomRight.longitude)
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [topLeftPredicate, bottomRightPredicate])
return self.filter(compoundPredicate)
}
/**
Filter results from Realm query using GeoBox
- parameter box: GeoBox struct
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Filtered objects inside GeoBox
*/
func filterGeoBox(box: GeoBox, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> Results<Element> {
// Realm instance pre-check
guard let _ = realm else { throw GeoQueriesError.invalidRealm("RLMRealm instance is needed to call this method") }
let topLeftPredicate = NSPredicate(format: "%K <= %f AND %K >= %f", latitudeKey, box.topLeft.latitude, longitudeKey, box.topLeft.longitude)
let bottomRightPredicate = NSPredicate(format: "%K >= %f AND %K <= %f", latitudeKey, box.bottomRight.latitude, longitudeKey, box.bottomRight.longitude)
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [topLeftPredicate, bottomRightPredicate])
return self.filter(compoundPredicate)
}
/**
Filter results from center and distance radius
- parameter center: Center coordinate
- parameter radius: Radius in meters
- parameter sort: Sort by distance (optionl)
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Found objects inside radius around the center coordinate
*/
func filterGeoRadius(center: CLLocationCoordinate2D, radius: Double, sortAscending sort: Bool?, latitudeKey: String = "lat", longitudeKey: String = "lng") throws -> [Element] {
// Realm instance pre-check
guard let _ = realm else { throw GeoQueriesError.invalidRealm("RLMRealm instance is needed to call this method") }
// Get box
let inBox = try filterGeoBox(box: center.geoBox(radius: radius), latitudeKey: latitudeKey, longitudeKey: longitudeKey)
// add distance
let distance = inBox.addDistance(center: center, latitudeKey: latitudeKey, longitudeKey: longitudeKey)
// Inside radius
let radius = distance.filter { (obj: Object) -> Bool in
return obj.objDist <= radius
}
// Sort results
guard let s = sort else { return radius }
return radius.sort(ascending: s)
}
/// Sort by distance
///
/// - Parameters:
/// - center: Center coordinate
/// - ascending: Ascendig or descending
/// - latitudeKey: Set to use different latitude key in query (default: "lat")
/// - longitudeKey: Set to use different longitude key in query (default: "lng")
/// - Returns: Sorted objects
func sortByDistance(center: CLLocationCoordinate2D, ascending: Bool, latitudeKey: String = "lat", longitudeKey: String = "lng") -> [Element] {
return self
.addDistance(center: center, latitudeKey: latitudeKey, longitudeKey: longitudeKey)
.sort(ascending: ascending)
}
}
// MARK: - Public core extensions
/// GeoBox struct. Set top-left and bottom-right coordinate to create a box
public struct GeoBox {
public var topLeft: CLLocationCoordinate2D
public var bottomRight: CLLocationCoordinate2D
public init(topLeft: CLLocationCoordinate2D, bottomRight: CLLocationCoordinate2D) {
self.topLeft = topLeft
self.bottomRight = bottomRight
}
}
public extension CLLocationCoordinate2D {
/**
Accessory function to convert CLLocationCoordinate2D to GeoBox
- parameter radius: Radius in meters
- returns: GeoBox struct
*/
func geoBox(radius: Double) -> GeoBox {
#if swift(>=4.2)
return MKCoordinateRegion(center: self, latitudinalMeters: radius * 2.0, longitudinalMeters: radius * 2.0).geoBox
#else
return MKCoordinateRegion.init(center: self, latitudinalMeters: radius * 2.0, longitudinalMeters: radius * 2.0).geoBox
#endif
}
}
public extension MKCoordinateRegion {
/// Accessory function to convert MKCoordinateRegion to GeoBox
var geoBox: GeoBox {
let maxLat = self.center.latitude + (self.span.latitudeDelta / 2.0)
let minLat = self.center.latitude - (self.span.latitudeDelta / 2.0)
let maxLng = self.center.longitude + (self.span.longitudeDelta / 2.0)
let minLng = self.center.longitude - (self.span.longitudeDelta / 2.0)
return GeoBox(
topLeft: CLLocationCoordinate2D(latitude: maxLat, longitude: minLng),
bottomRight: CLLocationCoordinate2D(latitude: minLat, longitude: maxLng)
)
}
}
private extension Array where Element: Object {
/**
Sorting function
- parameter ascending: Ascending/Descending
- returns: Array of [Object] sorted by distance
*/
func sort(ascending: Bool = true) -> [Iterator.Element] {
return self.sorted(by: { (a: Object, b: Object) -> Bool in
if ascending {
return a.objDist < b.objDist
} else {
return a.objDist > b.objDist
}
})
}
}
// MARK: - Private core extensions
private extension RealmCollection where Element: Object {
/**
Add distance to sort results
- parameter center: Center coordinate
- parameter latitudeKey: Set to use different latitude key in query (default: "lat")
- parameter longitudeKey: Set to use different longitude key in query (default: "lng")
- returns: Array of results sorted
*/
func addDistance(center: CLLocationCoordinate2D, latitudeKey: String = "lat", longitudeKey: String = "lng") -> [Element] {
return self.map { (obj) -> Element in
// Calculate distance
let location = CLLocation(latitude: obj.value(forKeyPath: latitudeKey) as! CLLocationDegrees, longitude: obj.value(forKeyPath: longitudeKey) as! CLLocationDegrees)
let center = CLLocation(latitude: center.latitude, longitude: center.longitude)
let distance = location.distance(from: center)
// Save
obj.objDist = distance
return obj
}
}
}
private extension Object {
private struct AssociatedKeys {
static var DistanceKey = "DistanceKey"
}
var objDist: Double {
get {
guard let value = objc_getAssociatedObject(self, &AssociatedKeys.DistanceKey) as? Double else { return 0.0 }
return value
}
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.DistanceKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
}