Mapbox + Turf.js 5.6.1 + HexgridHeatmap

by Sarah Godoshian

HTML

<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css">
<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://unpkg.com/[email protected]/rbush.min.js"></script>
<div id='map' style='width: 400px; height: 300px;'></div>

JavaScript

/** 
 * Creates a hexgrid-based vector heatmap on the specified map.
 * @constructor
 * @param {Map} map - The map object that this heatmap should add itself to and track.
 * @param {string} [layername=hexgrid-heatmap] - The layer name to use for the heatmap.
 * @param {string} [addBefore] - Name of a layer to insert this heatmap underneath.
 */
function HexgridHeatmap(map, layername, addBefore) {
    if(layername === undefined) layername = "hexgrid-heatmap";
    this.map = map;
    this.layername = layername;
    this._setupLayers(layername, addBefore);
    this._setupEvents();
    // Set up an R-tree to look for coordinates as they are stored in GeoJSON Feature objects
    this._tree = rbush(9,['["geometry"]["coordinates"][0]','["geometry"]["coordinates"][1]','["geometry"]["coordinates"][0]','["geometry"]["coordinates"][1]']);

    this._intensity = 8;
    this._spread = 0.1;
    this._minCellIntensity = 0; // Drop out cells that have less than this intensity
    this._maxPointIntensity = 20; // Don't let a single point have a greater weight than this
    this._cellDensity = 1;

    var thisthis = this;
    this._checkUpdateCompleteClosure = function(e) { thisthis._checkUpdateComplete(e); }
    this._calculatingGrid = false;
    this._recalcWhenReady = false;
}

HexgridHeatmap.prototype = {
    _setupLayers: function(layername, addBefore) {
        this.map.addLayer({
        'id': layername,
        'type': 'fill',
        'source': {
            type: 'geojson',
            data: { type: "FeatureCollection", features: [] }
        },
        'paint': {
          'fill-opacity': 1.0,
          'fill-color': {
            property: 'count',
            stops: [
              // Short rainbow blue
              [0, "rgba(0,185,243,0)"],
              [50, "rgba(0,185,243,0.24)"],
              [130, "rgba(255,223,0,0.3)"],
              [200, "rgba(255,105,0,0.3)"],
            ]
          }
        }
        }, addBefore);

        this.layer =...