Skip to content

Commit

Permalink
Tidy project and add more functions
Browse files Browse the repository at this point in the history
wip commit

add tiles

remove files

tidy project

tidy project

tidy project

qq
  • Loading branch information
wkh237 committed Dec 16, 2016
1 parent 6b5de01 commit 0075982
Show file tree
Hide file tree
Showing 23 changed files with 993 additions and 433 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules/
regions/
region-raw-image/
1 change: 0 additions & 1 deletion exps.json

This file was deleted.

35 changes: 29 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ var fs = require('fs');
var util = require('util');
var mkdirp = require('mkdirp');
var getDirName = require('path').dirname;
var enableCache = true;
var enableCache = false;
var cp = require('child_process').exec;
var bodyParser = require('body-parser');
var imgCache = {};

var regions = JSON.parse(require('fs').readFileSync('./regions.json'));

app.set('port', (process.env.PORT || 5000));

app.use('/public', express.static('public'));
Expand All @@ -25,6 +23,31 @@ app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});

app.get('/regions', function(req, res) {

try {
var regions = fs.readdir('./regions/', function(err, files) {
console.log(files)
var results = [];
for(var i in files) {
if(/\.json$/i.test(files[i])) {
var meta = './regions/'+files[i];
console.log('read region meta :', meta);
var region = JSON.parse(fs.readFileSync(meta));
region.name = String(files[i]).replace(/\.json$/i,'');
results.push(region);
}
}
res.send(results);
})

// res.send(files)
}catch(err) {
console.log(err.stack);
}

})

app.post('/bounds/:region', function(req, res) {
var region = req.params.region;
console.log(region,req.body)
Expand Down Expand Up @@ -234,7 +257,7 @@ function createTileFromRawImage(region, x, y, z, debug, cb) {
ctx.rect(0, 0, 256, 256);
ctx.fillStyle = '#F0F0F0';
ctx.fill();
ctx.fillStyle = '#777';
ctx.fillStyle = '#222';
ctx.font = '16px Arial';
ctx.fillText('OUT OF BOUND', 128, 128);
var bytes = tileImg.toBuffer(undefined, 3, ctx.PNG_FILTER_NONE);
Expand Down Expand Up @@ -285,7 +308,7 @@ function drawText(ctx,param, ox,oy, dx, dy, z) {
var coords = 'from (' + [Math.round(ox), Math.floor(oy)].join(', ') + ')';
var coords2 = 'to (' + [Math.round(ox+dx), Math.floor(oy + dy)].join(', ') + ')';
ctx.font = '16px Arial';
ctx.fillStyle = '#DDD';
ctx.fillStyle = '#333';
ctx.fillText(info, 8, 24);
ctx.fillText(coords, 8, 48);
ctx.fillText(coords2, 8, 64);
Expand All @@ -302,7 +325,7 @@ function generateTile(x,y,z) {
ctx.rect(0, 0, 256, 256);
ctx.fillStyle = '#F0F0F0';
ctx.fill();
ctx.fillStyle = '#777';
ctx.fillStyle = '#333';
ctx.font = '16px Arial';
ctx.fillText(coords, 24, 64);
ctx.strokeStyle = 'white';
Expand Down
164 changes: 164 additions & 0 deletions make-tiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
var Canvas = require('canvas');
var Image = Canvas.Image;
var moment = require('moment');
var fs = require('fs');
var util = require('util');
var mkdirp = require('mkdirp');
var getDirName = require('path').dirname;
var cp = require('child_process').exec;
let img = new Image;
let imageCache = {};

console.log(process.argv);

var regionName = process.argv[2];
var min = +process.argv[3];
var max = +process.argv[4];
var val = JSON.parse(fs.readFileSync('./regions/'+regionName+'.json')).bounds;
console.log(val)
console.log('generate tiles:', regionName, min+'x', '~', max+'x');
// get tms bounds for each zoom level
var total = 0;
var ranges = [];
for(var i = min; i <= max ; i++) {
var lt = getTileAtLatLng(val[0], i);
var rb = getTileAtLatLng(val[2], i);
var w = Math.abs(rb.x-lt.x);
var h = Math.abs(rb.y-lt.y);
ranges.push({
zoom : i,
lt : lt,
rb : rb,
width : w,
height : h,
number : w*h
});
total += w*h;
}
console.log('tiles needs to be generated :', total);
var now = 0;
for(var i=min;i<=max;i++) {
var lt = getTileAtLatLng(val[0], i);
var rb = getTileAtLatLng(val[2], i);
for(var j = lt.x; j < rb.x;j++){
for(var k=lt.y; k < rb.y;k++) {
createTileFromRawImage(regionName, j,k,i, function() {
});
}
}

}

function tileToLatLng(x,y,z) {
var result = { lat : tileToLat(y,z), lng : tileToLong(x,z) };;
return result;
}

function tileToLong(x,z) { return (x/Math.pow(2,z)*360-180); }

function tileToLat(y,z) {
var n = Math.PI-2*Math.PI*y/Math.pow(2,z);
return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
}

function createTileFromRawImage(region, x, y, z, cb) {
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
let bounds = fs.readFile(`./regions/${region}.json`, (err, data) => {

let {bounds} = JSON.parse(data);
let tileBounds = [
tileToLatLng(x,y,z),
tileToLatLng(x+1,y,z),
tileToLatLng(x+1,y+1,z),
tileToLatLng(x,y+1,z)
];
if(imageCache[region]) {
render(null, imageCache[region]);
}
else {
fs.readFile(`./region-raw-img/${region}.png`, render);
}

function render(err, data) {
if(!imageCache[region] )
imageCache[region] = data;
if(err)
throw err;
let img = new Image;
img.src = data;

let regionWidth = Math.abs(Math.abs(bounds[0].lng) - Math.abs(bounds[1].lng)),
regionHeight = Math.abs(Math.abs(bounds[1].lat) - Math.abs(bounds[2].lat));

let tileWidth = Math.abs(tileBounds[0].lng - tileBounds[1].lng) * img.width /regionWidth,
tileHeight = Math.abs(tileBounds[1].lat - tileBounds[2].lat) * img.height /regionHeight;

let tileImg = new Canvas(256, 256);
let originX = (Math.abs(tileBounds[0].lng) - Math.abs(bounds[0].lng))/regionWidth * img.width;
let originY = (Math.abs(tileBounds[0].lat) - Math.abs(bounds[0].lat))/regionHeight * img.height;
let ctx = tileImg.getContext('2d');

if( originX > img.width + tileWidth ||
originY > img.height + tileHeight ||
originY < -tileHeight -1 || originX < -tileWidth -1 ) {
return
}
else {
ctx.drawImage(img, originX, originY, tileWidth, tileHeight, 0, 0, 256, 256);
ctx.strokeStyle = 'transparent';
ctx.strokeRect(0, 0, 256, 256);
}

var bytes = tileImg.toBuffer(undefined, 3, ctx.PNG_FILTER_NONE);

var dir = `./regions/${region}/${z}/${x}${y}.png`;
mkdirp(getDirName(dir), function (err) {
if (err)
console.log(err);

fs.writeFile(dir, bytes, function(err) {
if(err)
console.log(err)
console.log('remaining tiles', --total);
cb();
});

});

}

});

}

var deleteFolderRecursive = function(path, cb) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
cb()
};

function fromLatLngToPoint (latLng){
var siny = Math.min(Math.max(Math.sin(latLng.lat* (Math.PI / 180)), -.9999),.9999);
return {
x: 128 + latLng.lng * (256/360),
y: 128 + 0.5 * Math.log((1 + siny) / (1 - siny)) * -(256 / (2 * Math.PI))
};
}

function getTileAtLatLng(latLng,zoom){
var t=Math.pow(2,zoom),
s=256/t,
p=fromLatLngToPoint(latLng);
return {x:Math.floor(p.x/s),y:Math.floor(p.y/s),z:zoom};
}
Loading

0 comments on commit 0075982

Please sign in to comment.