const fs = require('fs') const request = require('request') const path = require('path') const dirPath = path.join(__dirname, "baseMap"); function checkLocal(zoom, x, y) { return new Promise(resolve => { fs.exists(`${dirPath}/${zoom}_${x}_${y}.png`, resolve) }) } const downImage = (function() { let count = 0 const domains = [ 'http://a.tile.openstreetmap.org', 'http://b.tile.openstreetmap.org', 'http://c.tile.openstreetmap.org' ] const length = domains.length return async function downImage(zoom, x, y) { count++; let url = domains[count % length] + `/${zoom}/${x}/${y}.png` let local = `${dirPath}/${zoom}_${x}_${y}.png` return new Promise(resolve => { try { let readStream = request(url) let writeStream = fs.createWriteStream(local) readStream.on('error', errorHandle) function errorHandle(err) { console.error(err) resolve() } readStream.pipe(writeStream) .on('close', err => { if (err) { console.error(url + '文件下载失败') } else { console.log(url + '文件下载成功') } resolve() }) .on('error', errorHandle) } catch (e) { resolve() console.error(e) } }) } })(); async function cache(...args) { if (!(await checkLocal(...args))) { await downImage(...args) } } let setting = { 1: { minX: -1, maxX: 5, minY: -1, maxY: 5 }, 2: { minX: -1, maxX: 10, minY: -1, maxY: 10 }, 3: { minX: -1, maxX: 20, minY: -1, maxY: 20 }, 9: { minX: 200, maxX: 600, maxY: 100, maxY: 400 }, 10: { minX: 500, maxX: 1100, minY: 200, maxY: 600 }, 11: { minX: 1200, maxX: 2000, minY: 400, maxY: 1200 }, 12: { minX: 2300, maxX: 4300, minY: 1500, maxY: 2100 }, 13: { minX: 4600, maxX: 8600, minY: 2000, maxY: 4000 }, 14: { minX: 10000, maxX: 16600, minY: 5000, maxY: 8000 }, 15: { minX: 23000, maxX: 29000, minY: 10000, maxY: 16000 }, 16: { minX: 40000, maxX: 60000, minY: 23000, maxY: 31000 }, 17: { minX: 80000, maxX: 120000, minY: 50000, maxY: 62000 }, 18: { minX: 200000, maxX: 233000, minY: 80000, maxY: 130000 }, 19: { minX: 380000, maxX: 470000, minY: 180000, maxY: 250000 } } process.on('message', async msg => { let zoom = Number(msg) console.log(zoom) let {minX, maxX, minY, maxY} = setting[zoom] // let min = parseInt(basic / 4) // let maxX = basic * 10 // let maxY = maxX / 1.5 let total = (maxX - minX) * (maxY - minY) let count = 0 for (let x = maxX; x > minX; x--) { for (let y = minY; y < maxY && y < x;) { let run = y + 100 < maxY ? 100 : maxY - y let pros = [] for (let h = 0; h < run; h++) { count++ pros.push(cache(zoom, x, y + h)) } await Promise.all(pros) y += run console.log('层级' + zoom + '总共' + total + '已下载' + count) } } fs.writeFileSync('./log.text', fs.readFileSync('./log.text') + '\r\n' + '层级' + zoom + '已下载完毕') })