forked from tomayac/local-reverse-geocoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geocoder.js
executable file
·790 lines (742 loc) · 27.7 KB
/
geocoder.js
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/**
* @fileoverview Local reverse geocoder based on GeoNames data.
* @author Thomas Steiner ([email protected])
* @license Apache 2.0
*
* @param {(object|object[])} points One single or an array of
* latitude/longitude pairs
* @param {integer} maxResults The maximum number of results to return
* @callback callback The callback function with the results
*
* @returns {object[]} An array of GeoNames-based geocode results
*
* @example
* // With just one point
* var point = {latitude: 42.083333, longitude: 3.1};
* geocoder.lookUp(point, 1, function(err, res) {
* console.log(JSON.stringify(res, null, 2));
* });
*
* // In batch mode with many points
* var points = [
* {latitude: 42.083333, longitude: 3.1},
* {latitude: 48.466667, longitude: 9.133333}
* ];
* geocoder.lookUp(points, 1, function(err, res) {
* console.log(JSON.stringify(res, null, 2));
* });
*/
'use strict';
var debug = require('debug')('local-reverse-geocoder');
var fs = require('fs');
var path = require('path');
var parse = require('csv-parse');
var kdTree = require('kdt');
var request = require('request');
var unzip = require('node-unzip-2');
var async = require('async');
var readline = require('readline');
// All data from http://download.geonames.org/export/dump/
var GEONAMES_URL = 'http://download.geonames.org/export/dump/';
var CITIES_FILE = 'cities1000';
var ADMIN_1_CODES_FILE = 'admin1CodesASCII';
var ADMIN_2_CODES_FILE = 'admin2Codes';
var ALL_COUNTRIES_FILE = 'allCountries';
var ALTERNATE_NAMES_FILE = 'alternateNames';
/* jshint maxlen: false */
var GEONAMES_COLUMNS = [
'geoNameId', // integer id of record in geonames database
'name', // name of geographical point (utf8) varchar(200)
'asciiName', // name of geographical point in plain ascii characters, varchar(200)
'alternateNames', // alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
'latitude', // latitude in decimal degrees (wgs84)
'longitude', // longitude in decimal degrees (wgs84)
'featureClass', // see http://www.geonames.org/export/codes.html, char(1)
'featureCode', // see http://www.geonames.org/export/codes.html, varchar(10)
'countryCode', // ISO-3166 2-letter country code, 2 characters
'cc2', // alternate country codes, comma separated, ISO-3166 2-letter country code, 60 characters
'admin1Code', // fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
'admin2Code', // code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
'admin3Code', // code for third level administrative division, varchar(20)
'admin4Code', // code for fourth level administrative division, varchar(20)
'population', // bigint (8 byte int)
'elevation', // in meters, integer
'dem', // digital elevation model, srtm3 or gtopo30, average elevation 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
'timezone', // the timezone id (see file timeZone.txt) varchar(40)
'modificationDate', // date of last modification in yyyy-MM-dd format
];
/* jshint maxlen: 80 */
var GEONAMES_ADMIN_CODES_COLUMNS = [
'concatenatedCodes',
'name',
'asciiName',
'geoNameId'
];
/* jshint maxlen: false */
var GEONAMES_ALTERNATE_NAMES_COLUMNS = [
'alternateNameId', // the id of this alternate name, int
'geoNameId', // geonameId referring to id in table 'geoname', int
'isoLanguage', // iso 639 language code 2- or 3-characters; 4-characters 'post' for postal codes and 'iata','icao' and faac for airport codes, fr_1793 for French Revolution name
'alternateNames', // alternate name or name variant, varchar(200)
'isPreferrredName', // '1', if this alternate name is an official/preferred name
'isShortName', // '1', if this is a short name like 'California' for 'State of California'
'isColloquial', // '1', if this alternate name is a colloquial or slang term
'isHistoric' // '1', if this alternate name is historic and was used in the past
];
/* jshint maxlen: 80 */
var GEONAMES_DUMP = __dirname + '/geonames_dump';
var geocoder = {
_kdTree: null,
_admin1Codes: null,
_admin2Codes: null,
_admin3Codes: null,
_admin4Codes: null,
_alternateNames: null,
// Distance function taken from
// http://www.movable-type.co.uk/scripts/latlong.html
_distanceFunc: function distance(x, y) {
var toRadians = function(num) {
return num * Math.PI / 180;
};
var lat1 = x.latitude;
var lon1 = x.longitude;
var lat2 = y.latitude;
var lon2 = y.longitude;
var R = 6371; // km
var φ1 = toRadians(lat1);
var φ2 = toRadians(lat2);
var Δφ = toRadians(lat2 - lat1);
var Δλ = toRadians(lon2 - lon1);
var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
},
_getGeoNamesAlternateNamesData: function(callback) {
var now = (new Date()).toISOString().substr(0, 10);
// Use timestamped alternate names file OR bare alternate names file
var timestampedFilename = GEONAMES_DUMP + '/alternate_names/' +
ALTERNATE_NAMES_FILE + '_' + now + '.txt';
if (fs.existsSync(timestampedFilename)) {
debug('Using cached GeoNames alternate names data from ' +
timestampedFilename);
return callback(null, timestampedFilename);
}
var filename = GEONAMES_DUMP + '/alternate_names/' + ALTERNATE_NAMES_FILE +
'.txt';
if (fs.existsSync(filename)) {
debug('Using cached GeoNames alternate names data from ' +
filename);
return callback(null, filename);
}
debug('Getting GeoNames alternate names data from ' +
GEONAMES_URL + ALTERNATE_NAMES_FILE + '.zip (this may take a while)');
var options = {
url: GEONAMES_URL + ALTERNATE_NAMES_FILE + '.zip',
encoding: null
};
request.get(options, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback('Error downloading GeoNames alternate names data' +
(err ? ': ' + err : ''));
}
debug('Received zipped GeoNames alternate names data');
// Store a dump locally
if (!fs.existsSync(GEONAMES_DUMP + '/alternate_names')) {
fs.mkdirSync(GEONAMES_DUMP + '/alternate_names');
}
var zipFilename = GEONAMES_DUMP + '/alternate_names/' +
ALTERNATE_NAMES_FILE + '_' + now + '.zip';
try {
fs.writeFileSync(zipFilename, body);
fs.createReadStream(zipFilename)
.pipe(unzip.Extract({path: GEONAMES_DUMP + '/alternate_names'}))
.on('error', function(e) {
console.error(e);
})
.on('close', function() {
fs.renameSync(filename, timestampedFilename);
fs.unlinkSync(GEONAMES_DUMP + '/alternate_names/' +
ALTERNATE_NAMES_FILE + '_' + now + '.zip');
debug('Unzipped GeoNames alternate names data');
// Housekeeping, remove old files
var currentFileName = path.basename(timestampedFilename);
fs.readdirSync(GEONAMES_DUMP + '/alternate_names').forEach(
function(file) {
if (file !== currentFileName) {
fs.unlinkSync(GEONAMES_DUMP + '/alternate_names/' + file);
}
});
return callback(null, timestampedFilename);
});
} catch (e) {
debug('Warning: ' + e);
return callback(null, timestampedFilename);
}
});
},
_parseGeoNamesAlternateNamesCsv: function(pathToCsv, callback) {
var that = this;
that._alternateNames = {};
var lineReader = readline.createInterface({
input: fs.createReadStream(pathToCsv)
});
lineReader.on('line', function(line) {
line = line.split('\t');
const [
_,
geoNameId,
isoLanguage,
altName,
isPreferredName,
isShortName,
isColloquial,
isHistoric
] = line;
if (isoLanguage === '') {
// consider data without country code as invalid
return;
}
if (!that._alternateNames[geoNameId]) {
that._alternateNames[geoNameId] = {};
}
that._alternateNames[geoNameId][isoLanguage] = {
altName,
isPreferredName: Boolean(isPreferredName),
isShortName: Boolean(isShortName),
isColloquial: Boolean(isColloquial),
isHistoric: Boolean(isHistoric)
};
});
lineReader.on('close', function() {
return callback();
});
},
_getGeoNamesAdmin1CodesData: function(callback) {
var now = (new Date()).toISOString().substr(0, 10);
var timestampedFilename = GEONAMES_DUMP + '/admin1_codes/' +
ADMIN_1_CODES_FILE + '_' + now + '.txt';
if (fs.existsSync(timestampedFilename)) {
debug('Using cached GeoNames admin 1 codes data from ' +
timestampedFilename);
return callback(null, timestampedFilename);
}
var filename = GEONAMES_DUMP + '/admin1_codes/' + ADMIN_1_CODES_FILE +
'.txt';
if (fs.existsSync(filename)) {
debug('Using cached GeoNames admin 1 codes data from ' +
filename);
return callback(null, filename);
}
debug('Getting GeoNames admin 1 codes data from ' +
GEONAMES_URL + ADMIN_1_CODES_FILE + '.txt (this may take a while)');
var url = GEONAMES_URL + ADMIN_1_CODES_FILE + '.txt';
request.get(url, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback('Error downloading GeoNames admin 1 codes data' +
(err ? ': ' + err : ''));
}
// Store a dump locally
if (!fs.existsSync(GEONAMES_DUMP + '/admin1_codes')) {
fs.mkdirSync(GEONAMES_DUMP + '/admin1_codes');
}
try {
fs.writeFileSync(timestampedFilename, body);
// Housekeeping, remove old files
var currentFileName = path.basename(timestampedFilename);
fs.readdirSync(GEONAMES_DUMP + '/admin1_codes').forEach(function(file) {
if (file !== currentFileName) {
fs.unlinkSync(GEONAMES_DUMP + '/admin1_codes/' + file);
}
});
} catch (e) {
throw(e);
}
return callback(null, timestampedFilename);
});
},
_parseGeoNamesAdmin1CodesCsv: function(pathToCsv, callback) {
var that = this;
var lenI = GEONAMES_ADMIN_CODES_COLUMNS.length;
that._admin1Codes = {};
var lineReader = readline.createInterface({
input: fs.createReadStream(pathToCsv)
});
lineReader.on('line', function(line) {
line = line.split('\t');
for (var i = 0; i < lenI; i++) {
var value = line[i] || null;
if (i === 0) {
that._admin1Codes[value] = {};
} else {
that._admin1Codes[line[0]][GEONAMES_ADMIN_CODES_COLUMNS[i]] = value;
}
}
});
lineReader.on('close', function() {
return callback();
});
},
_getGeoNamesAdmin2CodesData: function(callback) {
var now = (new Date()).toISOString().substr(0, 10);
var timestampedFilename = GEONAMES_DUMP + '/admin2_codes/' +
ADMIN_2_CODES_FILE + '_' + now + '.txt';
if (fs.existsSync(timestampedFilename)) {
debug('Using cached GeoNames admin 2 codes data from ' +
timestampedFilename);
return callback(null, timestampedFilename);
}
var filename = GEONAMES_DUMP + '/admin2_codes/' + ADMIN_2_CODES_FILE +
'.txt';
if (fs.existsSync(filename)) {
debug('Using cached GeoNames admin 2 codes data from ' +
filename);
return callback(null, filename);
}
debug('Getting GeoNames admin 2 codes data from ' +
GEONAMES_URL + ADMIN_2_CODES_FILE + '.txt (this may take a while)');
var url = GEONAMES_URL + ADMIN_2_CODES_FILE + '.txt';
request.get(url, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback('Error downloading GeoNames admin 2 codes data' +
(err ? ': ' + err : ''));
}
// Store a dump locally
if (!fs.existsSync(GEONAMES_DUMP + '/admin2_codes')) {
fs.mkdirSync(GEONAMES_DUMP + '/admin2_codes');
}
try {
fs.writeFileSync(timestampedFilename, body);
// Housekeeping, remove old files
var currentFileName = path.basename(timestampedFilename);
fs.readdirSync(GEONAMES_DUMP + '/admin2_codes').forEach(function(file) {
if (file !== currentFileName) {
fs.unlinkSync(GEONAMES_DUMP + '/admin2_codes/' + file);
}
});
} catch (e) {
throw(e);
}
return callback(null, timestampedFilename);
});
},
_parseGeoNamesAdmin2CodesCsv: function(pathToCsv, callback) {
var that = this;
var lenI = GEONAMES_ADMIN_CODES_COLUMNS.length;
that._admin2Codes = {};
var lineReader = readline.createInterface({
input: fs.createReadStream(pathToCsv)
});
lineReader.on('line', function(line) {
line = line.split('\t');
for (var i = 0; i < lenI; i++) {
var value = line[i] || null;
if (i === 0) {
that._admin2Codes[value] = {};
} else {
that._admin2Codes[line[0]][GEONAMES_ADMIN_CODES_COLUMNS[i]] = value;
}
}
});
lineReader.on('close', function() {
return callback();
});
},
_getGeoNamesCitiesData: function(callback) {
var now = (new Date()).toISOString().substr(0, 10);
// Use timestamped cities file OR bare cities file
var timestampedFilename = GEONAMES_DUMP + '/cities/' + CITIES_FILE + '_' +
now + '.txt';
if (fs.existsSync(timestampedFilename)) {
debug('Using cached GeoNames cities data from ' +
timestampedFilename);
return callback(null, timestampedFilename);
}
var filename = GEONAMES_DUMP + '/cities/' + CITIES_FILE + '.txt';
if (fs.existsSync(filename)) {
debug('Using cached GeoNames cities data from ' +
filename);
return callback(null, filename);
}
debug('Getting GeoNames cities data from ' + GEONAMES_URL +
CITIES_FILE + '.zip (this may take a while)');
var options = {
url: GEONAMES_URL + CITIES_FILE + '.zip',
encoding: null
};
request.get(options, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback('Error downloading GeoNames cities data' +
(err ? ': ' + err : ''));
}
debug('Received zipped GeoNames cities data');
// Store a dump locally
if (!fs.existsSync(GEONAMES_DUMP + '/cities')) {
fs.mkdirSync(GEONAMES_DUMP + '/cities');
}
var zipFilename = GEONAMES_DUMP + '/cities/' + CITIES_FILE + '_' + now +
'.zip';
try {
fs.writeFileSync(zipFilename, body);
fs.createReadStream(zipFilename)
.pipe(unzip.Extract({path: GEONAMES_DUMP + '/cities'}))
.on('close', function() {
fs.renameSync(filename, timestampedFilename);
fs.unlinkSync(GEONAMES_DUMP + '/cities/' + CITIES_FILE + '_' + now +
'.zip');
debug('Unzipped GeoNames cities data');
// Housekeeping, remove old files
var currentFileName = path.basename(timestampedFilename);
fs.readdirSync(GEONAMES_DUMP + '/cities').forEach(function(file) {
if (file !== currentFileName) {
fs.unlinkSync(GEONAMES_DUMP + '/cities/' + file);
}
});
return callback(null, timestampedFilename);
});
} catch (e) {
debug('Warning: ' + e);
return callback(null, timestampedFilename);
}
});
},
_parseGeoNamesCitiesCsv: function(pathToCsv, callback) {
debug('Started parsing cities.txt (this may take a ' +
'while)');
var data = [];
var lenI = GEONAMES_COLUMNS.length;
var that = this;
var content = fs.readFileSync(pathToCsv);
parse(content, {delimiter: '\t', quote: ''}, function(err, lines) {
if (err) {
return callback(err);
}
lines.forEach(function(line) {
var lineObj = {};
for (var i = 0; i < lenI; i++) {
var column = line[i] || null;
lineObj[GEONAMES_COLUMNS[i]] = column;
}
data.push(lineObj);
});
debug('Finished parsing cities.txt');
debug('Started building cities k-d tree (this may take ' +
'a while)');
var dimensions = [
'latitude',
'longitude'
];
that._kdTree = kdTree.createKdTree(data, that._distanceFunc, dimensions);
debug('Finished building cities k-d tree');
return callback();
});
},
_getGeoNamesAllCountriesData: function(callback) {
var now = (new Date()).toISOString().substr(0, 10);
var timestampedFilename = GEONAMES_DUMP + '/all_countries/' +
ALL_COUNTRIES_FILE + '_' + now + '.txt';
if (fs.existsSync(timestampedFilename)) {
debug('Using cached GeoNames all countries data from ' +
timestampedFilename);
return callback(null, timestampedFilename);
}
var filename = GEONAMES_DUMP + '/all_countries/' + ALL_COUNTRIES_FILE +
'.txt';
if (fs.existsSync(filename)) {
debug('Using cached GeoNames all countries data from ' +
filename);
return callback(null, filename);
}
debug('Getting GeoNames all countries data from ' +
GEONAMES_URL + ALL_COUNTRIES_FILE + '.zip (this may take a while)');
var options = {
url: GEONAMES_URL + ALL_COUNTRIES_FILE + '.zip',
encoding: null
};
request.get(options, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback('Error downloading GeoNames all countries data' +
(err ? ': ' + err : ''));
}
debug('Received zipped GeoNames all countries data');
// Store a dump locally
if (!fs.existsSync(GEONAMES_DUMP + '/all_countries')) {
fs.mkdirSync(GEONAMES_DUMP + '/all_countries');
}
var zipFilename = GEONAMES_DUMP + '/all_countries/' + ALL_COUNTRIES_FILE +
'_' + now + '.zip';
try {
fs.writeFileSync(zipFilename, body);
fs.createReadStream(zipFilename)
.pipe(unzip.Extract({path: GEONAMES_DUMP + '/all_countries'}))
.on('close', function() {
fs.renameSync(filename, timestampedFilename);
fs.unlinkSync(GEONAMES_DUMP + '/all_countries/' +
ALL_COUNTRIES_FILE + '_' + now + '.zip');
debug('Unzipped GeoNames all countries data');
// Housekeeping, remove old files
var currentFileName = path.basename(timestampedFilename);
var directory = GEONAMES_DUMP + '/all_countries';
fs.readdirSync(directory).forEach(function(file) {
if (file !== currentFileName) {
fs.unlinkSync(GEONAMES_DUMP + '/all_countries/' + file);
}
});
return callback(null, timestampedFilename);
});
} catch (e) {
debug('Warning: ' + e);
return callback(null, timestampedFilename);
}
});
},
_parseGeoNamesAllCountriesCsv: function(pathToCsv, callback) {
debug('Started parsing all countries.txt (this may take ' +
'a while)');
var lenI = GEONAMES_COLUMNS.length;
var that = this;
// Indexes
var featureCodeIndex = GEONAMES_COLUMNS.indexOf('featureCode');
var countryCodeIndex = GEONAMES_COLUMNS.indexOf('countryCode');
var admin1CodeIndex = GEONAMES_COLUMNS.indexOf('admin1Code');
var admin2CodeIndex = GEONAMES_COLUMNS.indexOf('admin2Code');
var admin3CodeIndex = GEONAMES_COLUMNS.indexOf('admin3Code');
var admin4CodeIndex = GEONAMES_COLUMNS.indexOf('admin4Code');
var nameIndex = GEONAMES_COLUMNS.indexOf('name');
var asciiNameIndex = GEONAMES_COLUMNS.indexOf('asciiName');
var geoNameIdIndex = GEONAMES_COLUMNS.indexOf('geoNameId');
var counter = 0;
that._admin3Codes = {};
that._admin4Codes = {};
var lineReader = readline.createInterface({
input: fs.createReadStream(pathToCsv)
});
lineReader.on('line', function(line) {
line = line.split('\t');
var featureCode = line[featureCodeIndex];
if ((featureCode === 'ADM3') || (featureCode === 'ADM4')) {
var lineObj = {
name: line[nameIndex],
asciiName: line[asciiNameIndex],
geoNameId: line[geoNameIdIndex]
};
var key = line[countryCodeIndex] + '.' + line[admin1CodeIndex] + '.' +
line[admin2CodeIndex] + '.' + line[admin3CodeIndex];
if (featureCode === 'ADM3') {
that._admin3Codes[key] = lineObj;
} else if (featureCode === 'ADM4') {
that._admin4Codes[key + '.' + line[admin4CodeIndex]] = lineObj;
}
}
if (counter % 100000 === 0) {
debug('Parsing progress all countries ' + counter);
}
counter++;
});
lineReader.on('close', function() {
debug('Finished parsing all countries.txt');
return callback();
});
},
init: function(options, callback) {
options = options || {};
if (options.dumpDirectory) {
GEONAMES_DUMP = options.dumpDirectory;
}
options.load = options.load || {};
if (options.load.admin1 === undefined) {
options.load.admin1 = true;
}
if (options.load.admin2 === undefined) {
options.load.admin2 = true;
}
if (options.load.admin3And4 === undefined) {
options.load.admin3And4 = true;
}
if (options.load.alternateNames === undefined) {
options.load.alternateNames = true;
}
debug('Initializing local reverse geocoder using dump ' +
'directory: ' + GEONAMES_DUMP);
// Create local cache folder
if (!fs.existsSync(GEONAMES_DUMP)) {
fs.mkdirSync(GEONAMES_DUMP);
}
var that = this;
async.parallel([
// Get GeoNames cities
function(waterfallCallback) {
async.waterfall([
that._getGeoNamesCitiesData.bind(that),
that._parseGeoNamesCitiesCsv.bind(that)
], function() {
return waterfallCallback();
});
},
// Get GeoNames admin 1 codes
function(waterfallCallback) {
if (options.load.admin1) {
async.waterfall([
that._getGeoNamesAdmin1CodesData.bind(that),
that._parseGeoNamesAdmin1CodesCsv.bind(that)
], function() {
return waterfallCallback();
});
} else {
return setImmediate(waterfallCallback);
}
},
// Get GeoNames admin 2 codes
function(waterfallCallback) {
if (options.load.admin2) {
async.waterfall([
that._getGeoNamesAdmin2CodesData.bind(that),
that._parseGeoNamesAdmin2CodesCsv.bind(that)
], function() {
return waterfallCallback();
});
} else {
return setImmediate(waterfallCallback);
}
},
// Get GeoNames all countries
function(waterfallCallback) {
if (options.load.admin3And4) {
async.waterfall([
that._getGeoNamesAllCountriesData.bind(that),
that._parseGeoNamesAllCountriesCsv.bind(that)
], function() {
return waterfallCallback();
});
} else {
return setImmediate(waterfallCallback);
}
},
// Get GeoNames alternate names
function(waterfallCallback) {
if (options.load.alternateNames) {
async.waterfall([
that._getGeoNamesAlternateNamesData.bind(that),
that._parseGeoNamesAlternateNamesCsv.bind(that)
], function() {
return waterfallCallback();
});
} else {
return setImmediate(waterfallCallback);
}
}
],
// Main callback
function(err) {
if (err) {
throw(err);
}
return callback();
});
},
lookUp: function(points, arg2, arg3) {
var callback;
var maxResults;
if (arguments.length === 2) {
maxResults = 1;
callback = arg2;
} else {
maxResults = arg2;
callback = arg3;
}
this._lookUp(points, maxResults, function(err, results) {
return callback(null, results);
});
},
_lookUp: function(points, maxResults, callback) {
var that = this;
// If not yet initialied, then initialize
if (!this._kdTree) {
return this.init({}, function() {
return that.lookUp(points, maxResults, callback);
});
}
// Make sure we have an array of points
if (!Array.isArray(points)) {
points = [points];
}
var functions = [];
points.forEach(function(point, i) {
point = {
latitude: parseFloat(point.latitude),
longitude: parseFloat(point.longitude)
};
debug('Look-up request for point ' +
JSON.stringify(point));
functions[i] = function(innerCallback) {
var result = that._kdTree.nearest(point, maxResults);
result.reverse();
for (var j = 0, lenJ = result.length; j < lenJ; j++) {
if (result && result[j] && result[j][0]) {
var countryCode = result[j][0].countryCode || '';
var geoNameId = result[j][0].geoNameId || '';
var admin1Code;
var admin2Code;
var admin3Code;
var admin4Code;
// Look-up of admin 1 code
if (that._admin1Codes) {
admin1Code = result[j][0].admin1Code || '';
var admin1CodeKey = countryCode + '.' + admin1Code;
result[j][0].admin1Code = that._admin1Codes[admin1CodeKey] ||
result[j][0].admin1Code;
}
// Look-up of admin 2 code
if (that._admin2Codes) {
admin2Code = result[j][0].admin2Code || '';
var admin2CodeKey = countryCode + '.' + admin1Code + '.' +
admin2Code;
result[j][0].admin2Code = that._admin2Codes[admin2CodeKey] ||
result[j][0].admin2Code;
}
// Look-up of admin 3 code
if (that._admin3Codes) {
admin3Code = result[j][0].admin3Code || '';
var admin3CodeKey = countryCode + '.' + admin1Code + '.' +
admin2Code + '.' + admin3Code;
result[j][0].admin3Code = that._admin3Codes[admin3CodeKey] ||
result[j][0].admin3Code;
}
// Look-up of admin 4 code
if (that._admin4Codes) {
admin4Code = result[j][0].admin4Code || '';
var admin4CodeKey = countryCode + '.' + admin1Code + '.' +
admin2Code + '.' + admin3Code + '.' + admin4Code;
result[j][0].admin4Code = that._admin4Codes[admin4CodeKey] ||
result[j][0].admin4Code;
}
// Look-up of alternate name
if (that._alternateNames) {
result[j][0].alternateName = that._alternateNames[geoNameId] ||
result[j][0].alternateName;
}
// Pull in the k-d tree distance in the main object
result[j][0].distance = result[j][1];
// Simplify the output by not returning an array
result[j] = result[j][0];
}
}
debug('Found result(s) for point ' +
JSON.stringify(point) + result.map(function(subResult, i) {
return '\n (' + (++i) + ') {"geoNameId":"' +
subResult.geoNameId + '",' + '"name":"' + subResult.name +
'"}';
}));
return innerCallback(null, result);
};
});
async.series(
functions,
function(err, results) {
debug('Delivering joint results');
return callback(null, results);
});
}
};
module.exports = geocoder;