Created
September 29, 2017 13:31
-
-
Save mourner/14f52d4764299a8fcc204d699abdcc5b to your computer and use it in GitHub Desktop.
Quick example of generating GeoJSON contours from raster with d3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var contours = require('d3-contour').contours; | |
var PNG = require('pngjs').PNG; | |
var fs = require('fs'); | |
var png = PNG.sync.read(fs.readFileSync('./rain.png')); | |
var data = []; | |
for (var i = 0; i < png.height; i++) { | |
for (var j = 0; j < png.width; j++) { | |
data[i * png.width + j] = png.data[4 * (i * png.width + j) + 0]; | |
} | |
} | |
var zValues = [8, 18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198, 216, 234, 252]; | |
var polygons = contours() | |
.size([png.width, png.height]) | |
.thresholds(zValues) | |
(data); | |
var geojson = { | |
type: 'FeatureCollection', | |
features: [] | |
}; | |
for (let polygon of polygons) { | |
if (polygon.coordinates.length === 0) continue; | |
let coords = convertCoords(polygon.coordinates); | |
geojson.features.push({ | |
type: 'Feature', | |
properties: { | |
value: polygon.value | |
}, | |
geometry: { | |
type: polygon.type, | |
coordinates: coords | |
} | |
}) | |
} | |
function convertCoords(coords) { | |
var minLng = 63.8148899733; | |
var maxLng = 143.536486117; | |
var maxLat = 56.3833398551; | |
var minLat = 12.7700338517; | |
var result = []; | |
for (let poly of coords) { | |
var newPoly = []; | |
for (let ring of poly) { | |
if (ring.length < 4) continue; | |
var newRing = []; | |
for (let p of ring) { | |
newRing.push([ | |
minLng + (maxLng - minLng) * (p[0] / png.width), | |
maxLat - (maxLat - minLat) * (p[1] / png.height) | |
]); | |
} | |
newPoly.push(newRing); | |
} | |
result.push(newPoly); | |
} | |
return result; | |
} | |
console.log(JSON.stringify(geojson)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@agdhruv - hopefully this will help