Skip to content

Instantly share code, notes, and snippets.

@adamzwakk
Created September 9, 2019 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamzwakk/bf240a154072208bb1f0445d5c8ccb7c to your computer and use it in GitHub Desktop.
Save adamzwakk/bf240a154072208bb1f0445d5c8ccb7c to your computer and use it in GitHub Desktop.
Node.JS script to generate map tiles from a source image for leaflet.js
// node .\tools\generate-map.js --bigfile .\src\fullmap.jpg --endpath .\public\grid\ --zoom 7
const fs = require('fs');
const sharp = require('sharp');
const argv = require('yargs').argv;
const _cliProgress = require('cli-progress');
const endPresentFile = argv.bigfile;
const gridPath = argv.endpath;
const bar1 = new _cliProgress.SingleBar({}, _cliProgress.Presets.shades_classic);
let gridDims = 256;
let zoomLevels = argv.zoom;
let generateGridPiece = function(image,x,y){
return new Promise(resolve => {
image.extract({left:x*gridDims,top:y*gridDims,width:gridDims,height:gridDims}).toFile(path+y+'.jpg').then(function(){
resolve(true);
});
});
}
async function go(){
console.log('This will take a while...')
let bigFile = sharp(endPresentFile).limitInputPixels(false);
for (var z = zoomLevels; z >= 0; z--) {
if (!fs.existsSync(gridPath+z)){
fs.mkdirSync(gridPath+z);
}
let tWidth = gridDims;
let tHeight = gridDims;
let pieces = 1;
if(z > 0){
pieces = Math.pow(2,z+1)/2;
percent = z/zoomLevels;
tWidth = pieces*gridDims;
tHeight = pieces*gridDims;
}
console.log('Starting zoom level '+z+' at '+pieces+'x'+pieces+' ('+tWidth+'x'+tHeight+')');
let resized = bigFile.clone().resize({width:tWidth,height:tHeight});
bar1.start(Math.pow(pieces,2),0);
for (var x = 0; x < pieces; x++) {
path = gridPath+z+'/'+x+'/';
if (!fs.existsSync(path)){
fs.mkdirSync(path);
}
for (var y = 0; y < pieces; y++) {
var gridpiece = await generateGridPiece(resized,x,y);
bar1.increment();
}
}
bar1.stop();
}
}
go();
{
"dependencies": {
"cli-progress": "^3.1.0",
"sharp": "^0.23.0",
"yargs": "^14.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment