Skip to content

Instantly share code, notes, and snippets.

@tai2
Created October 21, 2014 09:57
Show Gist options
  • Select an option

  • Save tai2/64c34e781f784d3eb5fe to your computer and use it in GitHub Desktop.

Select an option

Save tai2/64c34e781f784d3eb5fe to your computer and use it in GitHub Desktop.
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var sprintf = require('sprintf-js').sprintf;
var jsonfile = require('jsonfile');
var Canvas = require('canvas');
var Terraformer = require('terraformer');
var dirname = './geojson-2';
var files = fs.readdirSync(dirname);
files.forEach(function(filename) {
if (path.extname(filename) === '.json') {
draw(dirname + '/' + filename);
}
});
function draw(json_path) {
var canvas = new Canvas(512, 512);
var ctx = canvas.getContext('2d');
var EarthRadius = 6378137;
var bbox;
var geojson = new Terraformer.Primitive(jsonfile.readFileSync(json_path));
if (true || geojson.type === 'FeatureCollection') {
bbox = geojson.bbox();
geojson.features.forEach(function(feature) {
if (feature.type === 'Feature') {
if (feature.geometry.type === 'MultiPolygon') {
feature.geometry.coordinates.forEach(drawPolygon);
} else if (feature.geometry.type === 'Polygon') {
drawPolygon(feature.geometry.coordinates);
}
} else {
}
});
ctx.font = '14px sans-serif';
ctx.fillStyle = 'rgba(0,0,0,1.0)';
ctx.fillText(sprintf('(%.2f, %.2f) - (%.2f, %.2f)', bbox[0], bbox[1], bbox[2], bbox[3]), 10, 20);
var png_path = path.join(path.dirname(json_path), path.basename(json_path, '.json') + '.png');
fs.writeFileSync(png_path, canvas.toBuffer());
} else {
console.err('File type is not feature collection');
}
function drawPolygon(polygon) {
var exterior = polygon[0];
var m_min = Terraformer.Tools.positionToMercator([bbox[0], bbox[1]]);
var m_max = Terraformer.Tools.positionToMercator([bbox[2], bbox[3]]);
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.beginPath();
ctx.moveTo(exterior[0][0], exterior[0][1]);
exterior.forEach(function(coord) {
var m_coord = Terraformer.Tools.positionToMercator(coord);
var x = (m_coord[0] - m_min[0]) / (m_max[0] - m_min[0]);
var y = (m_coord[1] - m_min[1]) / (m_max[1] - m_min[1]);
ctx.lineTo(x * canvas.width, canvas.height - y * canvas.height);
});
ctx.closePath();
ctx.fill();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment