-
Notifications
You must be signed in to change notification settings - Fork 3
/
scrapeTiles.js
65 lines (57 loc) · 1.56 KB
/
scrapeTiles.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
const fs = require('fs');
const fetch = require('node-fetch');
let PARAMETERS = {
"TILE_URL": "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
"ZOOM": 2,
"TILE_FOLDER": "tiles/"
};
main();
function getMapTileUrl(x, y, z, options = {}) {
if (options.resolution == null) {
options.resolution = 4;
}
return PARAMETERS.TILE_URL
.replace("{x}", x)
.replace("{y}", y)
.replace("{z}", z)
.replace("{resolution}", options.resolution);
}
function main() {
readParameters().then(downloadTiles);
}
function readParameters() {
return new Promise(resolve => {
let filePath = process.argv.length >= 3 ? process.argv[2] : "parameters.json";
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error("Cannot read parameters.json", err);
process.exit();
}
PARAMETERS = JSON.parse(data);
resolve(PARAMETERS);
});
});
}
function downloadTiles() {
let z = PARAMETERS.ZOOM;
if (!fs.existsSync(PARAMETERS.TILE_FOLDER)) {
fs.mkdirSync(PARAMETERS.TILE_FOLDER);
}
for (let x = 0; x < 2 ** z; x++) {
for (let y = 0; y < 2 ** z; y++) {
let fileName = PARAMETERS.TILE_FOLDER + x + "_" + y + ".png";
downloadTile(x, y, z, fileName);
}
}
}
function downloadTile(x, y, z, fileName) {
fetch(getMapTileUrl(x, y, z))
.then(image =>
image.body.pipe(fs.createWriteStream(fileName))
.on('close', () => console.log('image ' + fileName + ' downloaded')))
.catch(() => {
setTimeout(() => {
downloadTile(x, y, z, fileName);
}, 1000);
});
}