-
Notifications
You must be signed in to change notification settings - Fork 0
/
getCounty.ts
63 lines (51 loc) · 1.94 KB
/
getCounty.ts
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
import fetch from 'node-fetch';
import { SearchPlace } from './searchPlace';
import { writeJsonFile, readJsonFile } from './files';
import fs from 'fs';
const getRegions = async () => {
const response = await fetch('https://www.overpass-api.de/api/interpreter?[out:json];{{geocodeArea:New Zealand}}->.searchArea;(relation["boundary"="administrative"]["admin_level"="4"](area.searchArea););out;')
const json = await response.json();
await writeJsonFile('regions.json', json)
}
export const getCounty = async (lat: number, lng: number) => {
const url = `https://nominatim.openstreetmap.org/reverse.php?lat=${lat}&lon=${lng}&zoom=8&format=jsonv2&addressdetails=0`;
const request = await fetch(url);
const response = await request.json();
return response.name;
}
export const getCounties = async (places: SearchPlace[]) => {
const result: { [id: string]: string } = fs.existsSync('data/counties.json')
? require('./data/counties.json')
: {};
const logProgress = (done: number) => {
console.log(`Done ${done}/${places.length} (${Math.round(done / places.length * 10000) / 100}%)`);
}
const dumpEvery = 10;
for (let i = 0; i < places.length; ++i) {
logProgress(i);
const place = places[i];
if (place.county)
continue;
const id = `${place.lat}_${place.lon}`;
if (result[id]) {
place.county = result[id];
continue;
}
try {
const county = await getCounty(place.lat, place.lon);
place.county = county;
result[id] = county;
} catch {
}
if ((i + 1) % dumpEvery === 0) {
await writeJsonFile('data/counties.json', result);
}
}
return result;
}
(async () => {
getRegions()
const places = require('./data/min_nz_places.json');
const counties = getCounties(places);
writeJsonFile('data/counties.json', counties);
})();