-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRGReverseGeocoder.m
517 lines (426 loc) · 15 KB
/
RGReverseGeocoder.m
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//
// RGReverseGeocoder.m
// ReverseGeocoding
//
// Created by Daniel Rodríguez Troitiño on 27/03/09.
// Copyright 2009 Daniel Rodríguez Troitiño.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/*
* Parts of this file are "inspired" in SQLitePersistentObjects
* http://code.google.com/p/sqlitepersistentobjects/
*/
#import "RGReverseGeocoder.h"
#include <zlib.h>
#include <sys/mman.h>
#include "RGConfig.h"
#define MAX_DISTANCE_ON_EARTH 21000.0
#define EARTH_RADIUS 6378.0
#define RGLogX(s, ...) NSLog(@"%s - " s, __PRETTY_FUNCTION__, ##__VA_ARGS__)
#if defined(DEBUG)
# define RGLog(s, ...) RGLogX(s, ##__VA_ARGS__)
#else
# define RGLog(s, ...)
#endif
/** Shared instance */
static RGReverseGeocoder *sharedInstance = nil;
#pragma mark Private interface
@interface RGReverseGeocoder ()
@property (nonatomic, assign) sqlite3 *database;
@property (nonatomic, assign) int level;
/**
* Init a RGReverseGeocoder with the default database.
*/
- (id)init;
/**
* Check that the database file is current with the actual implementation.
* This checks against the <databaseFile>.plist that the schema version is
* supported.
*/
- (BOOL)checkDatabaseMetadata;
/**
* Returns the row or column of the sector from the latitude or the longitude.
*/
- (int)sectorFromCoordinate:(double)coordinate;
/**
* Returns the Hilbert curve distance of a sector.
*/
- (int)hilbertDistanceForRow:(int)row column:(int)column;
@end
#pragma mark Local methods
/**
* Returns the path of the default database file.
* This path is <NSDocumentDirectory>/geodata.sqlite.
*/
NSString *defaultDatabaseFile() {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] == 0) {
RGLogX(@"Application Support directory in User Domain not found.");
return nil;
}
NSString *defaultPath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:DATABASE_FILENAME];
return defaultPath;
}
/**
* Check that the values on both the metadata files are the same.
*/
BOOL checkSameMetadataValues(NSString *file1, NSString *file2) {
NSString *error;
NSPropertyListFormat format;
NSData *metadataData;
NSDictionary *metadata;
metadataData = [NSData dataWithContentsOfFile:file1];
metadata = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:metadataData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if (!metadata) {
RGLogX(@"Application database metadata failed to load with error '%@'.", error);
return NO;
}
NSNumber *schemaVersion1 = [metadata objectForKey:@"schema_version"];
NSString *databaseVersion1 = [metadata objectForKey:@"database_version"];
NSNumber *databaseLevel1 = [metadata objectForKey:@"database_level"];
metadataData = [NSData dataWithContentsOfFile:file2];
metadata = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:metadataData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if (!metadata) {
RGLogX(@"Application support database metadata failed to load with error '%@'.", error);
return NO;
}
NSNumber *schemaVersion2 = [metadata objectForKey:@"schema_version"];
NSString *databaseVersion2 = [metadata objectForKey:@"database_version"];
NSNumber *databaseLevel2 = [metadata objectForKey:@"database_level"];
return [schemaVersion1 isEqualToNumber:schemaVersion2] &&
[databaseLevel1 isEqualToNumber:databaseLevel2] &&
[databaseVersion1 isEqualToString:databaseVersion2];
}
/**
* Decompress a gzip compressed file into the destination file.
*/
BOOL decompressFile(NSString *origFile, NSString *destFile) {
BOOL done = NO;
char *buffer;
int bufferSize;
gzFile inFile = gzopen([origFile UTF8String], "rb");
if (!inFile) {
RGLog(@"Can not read origin database");
return NO;
}
NSOutputStream *outFile = [NSOutputStream outputStreamToFileAtPath:destFile append:NO];
if (!outFile) {
RGLog(@"Can not create destination database");
gzclose(inFile);
return NO;
}
[outFile open];
buffer = mmap(NULL, 256*1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
bufferSize = 256*1024;
if (buffer == (char *)(-1)) {
buffer = malloc(16*1024);
bufferSize = 16*1024;
}
while(1) {
int readLen = gzread(inFile, buffer, bufferSize);
if (!readLen) { /* end of file */
done = YES;
break;
}
if (readLen < 0) { /* error */
RGLog("Read error decompressing data");
break;
}
if (outFile) {
int writeLen = [outFile write:(const uint8_t *)buffer maxLength:readLen];
if (writeLen < readLen) {
RGLog("Write error decompressing data with error (%d) '%@'",
[[outFile streamError] code], [[outFile streamError] description]);
break;
}
}
}
if (bufferSize == 16*1024) {
free(buffer);
} else {
munmap(buffer, bufferSize);
}
gzclose(inFile);
[outFile close];
return done;
}
/**
* Returns the spherical distance between two points.
*/
double sphericalDistance(double lat1, double lon1, double lat2, double lon2) {
/* Convert all to radians */
lat1 = (lat1/180) * M_PI;
lon1 = (lon1/180) * M_PI;
lat2 = (lat2/180) * M_PI;
lon2 = (lon2/180) * M_PI;
double clat1 = cos(lat1);
double clon1 = cos(lon1);
double clat2 = cos(lat2);
double clon2 = cos(lon2);
double slat1 = sin(lat1);
double slon1 = sin(lon1);
double slat2 = sin(lat2);
double slon2 = sin(lon2);
return EARTH_RADIUS*(acos(clat1*clon1*clat2*clon2 +
clat1*slon1*clat2*slon2 +
slat1*slat2));
}
@implementation RGReverseGeocoder
@synthesize database = database_;
@synthesize level = level_;
#pragma mark Class methods
+ (id)sharedGeocoder {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
}
+ (BOOL)setupDatabase {
NSString *appResourcesPath = [[NSBundle mainBundle] resourcePath];
NSString *dbPath = [appResourcesPath stringByAppendingPathComponent:DATABASE_FILENAME @".gz"];
NSString *plistPath = [appResourcesPath stringByAppendingPathComponent:DATABASE_FILENAME @".plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager isReadableFileAtPath:dbPath] ||
![fileManager isReadableFileAtPath:plistPath]) {
RGLog(@"Compressed database or metadata are not readable from application bundle");
return NO;
}
NSString *dbDestPath = defaultDatabaseFile();
if (!dbDestPath) {
RGLog(@"Can not find application support directory");
return NO;
}
NSString *plistDestPath = [dbDestPath stringByAppendingString:@".plist"];
if (![fileManager fileExistsAtPath:dbDestPath] ||
![fileManager fileExistsAtPath:plistDestPath] ||
!checkSameMetadataValues(plistPath, plistDestPath)) {
NSError *error = nil;
if([fileManager fileExistsAtPath:plistDestPath]) {
if (![fileManager removeItemAtPath:plistDestPath error:&error]) {
RGLog(@"'%@' already exist and can not be removed with error (%d) '%@'",
plistDestPath, [error code], [error description]);
return NO;
}
}
if (![fileManager copyItemAtPath:plistPath toPath:plistDestPath error:&error]) {
RGLog(@"Can not copy metadata file with error (%d) '%@'",
[error code], [error description]);
return NO;
}
if (!decompressFile(dbPath, dbDestPath)) {
RGLog(@"Can not decompress database file");
return NO;
}
}
/* The destination files exist and they seem to be up-to-date versions, or
we have copied the files succesfully */
return YES;
}
#pragma mark Public instance methods
- (id)initWithDatabase:(NSString *)databasePath {
if (self = [super init]) {
databasePath_ = [databasePath copy];
if (![self checkDatabaseMetadata]) {
RGLogX(@"Database schema version for '%@' database differs", databasePath_);
[databasePath_ release];
return nil;
}
}
return self;
}
- (NSString *)placeForLocation:(CLLocation *)location {
return [self placeForLatitude:location.coordinate.latitude
longitude:location.coordinate.longitude];
}
- (NSString *)placeForLatitude:(double)latitude longitude:(double)longitude {
NSString *fallback = [NSString stringWithFormat:@"%f, %f",
latitude, longitude];
int row = [self sectorFromCoordinate:latitude];
int col = [self sectorFromCoordinate:longitude];
// Get the eight sectors around the central one
NSMutableArray *sectors = [[[NSMutableArray alloc] init] autorelease];
int sector;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (row+i < 0 || row+i >= mapDimension_ || col+j < 0 || col+j >= mapDimension_) {
continue;
}
sector = [self hilbertDistanceForRow:row+i column:col+j];
[sectors addObject:[NSNumber numberWithInt:sector]];
}
}
NSMutableString *query = [[[NSMutableString alloc] init] autorelease];
[query appendString:@"SELECT cities.name, countries.name, latitude, longitude "
"FROM cities JOIN countries ON cities.country_id = countries.id "
"WHERE sector IN ("];
BOOL first = YES;
for(NSNumber *s in sectors) {
[query appendFormat:@"%@%d", (first ? @"" : @", "), [s intValue]];
first = NO;
}
[query appendString:@")"];
sqlite3 *db = self.database;
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
RGLog(@"Can not prepare SQlite statement with error '%s'.", sqlite3_errmsg(db));
return fallback;
}
NSString *name = nil, *country = nil;
double minDistance = MAX_DISTANCE_ON_EARTH;
#if defined(DEBUG)
double maxDistance = 0.0;
#endif
while (sqlite3_step(stmt) == SQLITE_ROW) {
double lat = sqlite3_column_double(stmt, 2);
double lon = sqlite3_column_double(stmt, 3);
double distance = sphericalDistance(latitude, longitude,
lat, lon);
if (distance < minDistance) {
minDistance = distance;
const char *text = (const char *)sqlite3_column_text(stmt, 0);
if (text == nil) {
RGLog(@"Row without name!?");
sqlite3_finalize(stmt);
if (country) [country release];
return fallback;
}
name = [NSString stringWithUTF8String:text];
text = (const char *)sqlite3_column_text(stmt, 1);
if (text == nil) {
RGLog(@"Row without country!?");
sqlite3_finalize(stmt);
if (name) [name release];
return fallback;
}
country = [NSString stringWithUTF8String:text];
}
#if defined(DEBUG)
if (distance > maxDistance) {
maxDistance = distance;
}
#endif
}
sqlite3_finalize(stmt);
RGLog(@"Minimun distance: %f", minDistance);
#if defined(DEBUG)
RGLog(@"Maximun distance: %f", maxDistance);
#endif
if (name != nil && country != nil) {
return [NSString stringWithFormat:@"%@, %@", name, country];
} else {
return fallback;
}
}
- (void)setLevel:(int)newLevel {
if (level_ != newLevel) {
level_ = newLevel;
mapDimension_ = pow(2, level_);
}
}
#pragma mark Private instance methods
- (id)init {
return [self initWithDatabase:defaultDatabaseFile()];
}
- (BOOL)checkDatabaseMetadata {
NSString *plistFile = [databasePath_ stringByAppendingString:@".plist"];
NSData *metadataData = [NSData dataWithContentsOfFile:plistFile];
NSString *error;
NSPropertyListFormat format;
NSDictionary *metadata =
(NSDictionary *)[NSPropertyListSerialization
propertyListFromData:metadataData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if (!metadata) {
RGLogX(@"Database metadata failed to load with error '%@'.", error);
return NO;
}
NSNumber *databaseSchemaVersion = [metadata objectForKey:@"schema_version"];
if ([databaseSchemaVersion intValue] != SCHEMA_VERSION) {
return NO;
}
schemaVersion_ = [databaseSchemaVersion intValue];
databaseVersion_ = [[metadata objectForKey:@"database_version"] retain];
self.level = [[metadata objectForKey:@"database_level"] intValue];
return YES;
}
- (int)sectorFromCoordinate:(double)coordinate {
// We suppose latitude is also [-180, 180] so the sectors are squares
coordinate += 180;
return mapDimension_ * coordinate / 360.0;
}
- (int)hilbertDistanceForRow:(int)x column:(int)y {
int s = 0;
int xi, yi, temp;
for(int i = level_; i >= 0; i--) {
xi = (x >> i) & 1; /* Get bit i of x */
yi = (y >> i) & 1; /* Get bit i of y */
if (yi == 0) {
temp = x; /* Swap x and y and, */
x = y ^ (-xi); /* if xi = 1 */
y = temp ^ (-xi); /* complement them. */
}
s = 4*s + 2*xi + (xi ^ yi); /* Append two bits to s. */
}
return s;
}
/**
* Returns the database handle.
* Opens the database if it is neccesary.
*/
- (sqlite3 *)database {
static BOOL first = YES;
if (first || database_ == NULL) {
first = NO;
if (sqlite3_open([databasePath_ UTF8String], &database_) != SQLITE_OK) {
// Even though the open failed, call close to properly clean up resources.
RGLogX(@"Failed to open database with message '%s'.", sqlite3_errmsg(database_));
sqlite3_close(database_);
} else {
// Default to UTF-8 encoding
char *errorMsg;
NSString *sql = @"PRAGMA encoding = \"UTF-8\"";
if (sqlite3_exec(database_, [sql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
RGLogX(@"Failed to execute SQL '%@' with message '%s'.", sql, errorMsg);
sqlite3_free(errorMsg);
}
}
}
return database_;
}
- (void)dealloc {
if (database_) {
sqlite3_close(database_);
}
[databasePath_ release];
[super dealloc];
}
@end