jsfreemaplib
Version:
Miscellaneous JavaScript classes and functions for working with geodata, including working with Spherical Mercator projection and managing XYZ tiles, plus some general UI functions.
69 lines (59 loc) • 2.39 kB
JavaScript
// from aframe-osm-3d - added to jsfreemaplib 0.3.x
const Tiler = require('./Tiler');
const PNG = require('pngjs').PNG;
const DEM = require('./DEM');
class DemTiler extends Tiler {
constructor(url) {
super(url);
this.allDems = { };
}
async readTile(url) {
return new Promise ( (resolve, reject) => {
const arrbuf = fetch(url).then(res => res.arrayBuffer()).then
(arrbuf => {
const png = new PNG();
png.parse(arrbuf, (err, data) => {
if(err) reject(err);
let i;
const elevs = [];
for(let y = 0; y < png.height; y++) {
for(let x = 0; x < png.width; x++) {
i = (y * png.width + x) << 2;
elevs.push(Math.round((png.data[i] * 256 + png.data[i+1] + png.data[i+2] / 256) - 32768));
}
}
resolve( { w: png.width,
h: png.height,
elevs: elevs } );
});
});
});
}
// New in 0.4.3, allows lookup of elevation for arbitrary points
getElevation(sphMercPos) {
const tile = this.getTile(sphMercPos, this.tile.z);
const indexedTile = this.indexedTiles[`${tile.z}/${tile.x}/${tile.y}`];
if(indexedTile) {
return indexedTile.getHeight(sphMercPos[0], sphMercPos[1]);
}
return Number.NEGATIVE_INFINITY;
}
getElevationFromLonLat(lon, lat) {
return this.getElevation(this.sphMerc.project(lon, lat));
}
// Overridden to store each tile as a DEM object
_rawTileToStoredTile(tile, data) {
const topRight = tile.getTopRight();
const bottomLeft = tile.getBottomLeft();
const xSpacing = (topRight[0] - bottomLeft[0]) / (data.w-1);
const ySpacing = (topRight[1] - bottomLeft[1]) / (data.h-1);
const dem = new DEM (data.elevs,
bottomLeft,
data.w,
data.h,
xSpacing,
ySpacing);
return dem;
}
}
module.exports = DemTiler;