All this documentation is about representing raster data. In GIS, a raster is basically a 2-dimension matrix with the value of a magnitude in each point. The position over the Globe for each pixel (or matrix position) is given by the GeoTransform, and those positions are in a specific projection.

There are different ways to use a 2D matrix in JavaScript, and here I’ll be using the easiest one, an array of arrays. So, if the data is in a 1D array, can be transformed by:

var tempData = new Array(geotiffHeight);
  for (var j = 0; j<geotiffHeight; j++){
      tempData[j] = new Array(geotiffWidth);
      for (var i = 0; i<geotiffWidth; i++){
          tempData[j][i] = rasterArray[i + j*geotiffWidth];
      }
  }

GeoTIFF

There are many GIS raster formats, but reading them in JavaScript is quite difficult. There is no library like GDAL that works in pure JavaScript. Working with Nodejs you can try GDAL for Nodejs, but the tutorial tries to show how to draw with the broswer too.

Fortunately, the most used format, GeoTIFF, can be read using the geotiff.js library. Some options are still not implemented, but most of the files can be read perfectly, which is a great advance. To read the GeoTIFF file and create a matrix:

d3.request("tz850.tiff")
.responseType('arraybuffer')
.get(function(error, tiffData){
    var tiff = GeoTIFF.parse(tiffData.response);
    var image = tiff.getImage();
    var rasters = image.readRasters();
    var tiepoint = image.getTiePoints()[0];
    var pixelScale = image.getFileDirectory().ModelPixelScale;
    var geoTransform = [tiepoint.x, pixelScale[0], 0, tiepoint.y, 0, -1*pixelScale[1]];
    var invGeoTransform = [-geoTransform[0]/geoTransform[1], 1/geoTransform[1],0,-geoTransform[3]/geoTransform[5],0,1/geoTransform[5]];

    var tempData = new Array(image.getHeight());
    for (var j = 0; j<image.getHeight(); j++){
        tempData[j] = new Array(image.getWidth());
        for (var i = 0; i<image.getWidth(); i++){
            tempData[j][i] = rasters[1][i + j*image.getWidth()];
        }
    }
});

See the complete working example here

  • Note that the GeoTIFF file data must be read as an arraybuffer
  • The example file has two layers (or bands). In the example, we want the second one, that represents temperature, so rasters[1] is the actual array to be processed
  • The example shows how to calculate the GeoTransform and the inverse geotransform (how to calculate the pixel from the geographic coordinates)

If used from nodejs, the form to read the file is slightly different, since the fs functions are used:

var fs = require("fs");
var geotiff = require("geotiff");

var parser = geotiff.parse(dataArray);
var image = parser.getImage();
var rasters = image.readRasters();

The other parts of the code are the same.