Search code examples
javascriptmapboxdeck.gl

Deck.gl HexagonLayer tooltip with standard Javascript


I have the following code that groups latitude's and longitude's into hexbins and draws them on a map using a mapbox base map with a deck.gl layer on top of it:

<!doctype html>
<html lang="en">
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
  <!-- deck.gl standalone bundle -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist.min.js"></script>

  <!-- d3 -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script>

  <!-- Mapbox dependencies -->
  <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.js"></script>
  <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.css" rel="stylesheet" />
  <style>
    body {
      width: 100vw;
      height: 100vh;
      margin: 0;
    }

    #control-panel {
      font-family: Helvetica, Arial, sans-serif;
      position: absolute;
      background: #fff;
      top: 0;
      left: 0;
      margin: 12px;
      padding: 20px;
      z-index: 1;
    }

    label {
      display: inline-block;
      width: 140px;
    }
  </style>
</head>
  <body>
  <div id="control-panel">
    <div>
      <label>Radius</label>
      <input id="radius" type="range" min="1000" max="20000" step="1000" value="1000"></input>
      <span id="radius-value"></span>
    </div>
    <div>
      <label>Coverage</label>
      <input id="coverage" type="range" min="0" max="1" step="0.1" value="1"></input>
      <span id="coverage-value"></span>
    </div>
    <div>
      <label>Upper Percentile</label>
      <input id="upperPercentile" type="range" min="90" max="100" step="1" value="100"></input>
      <span id="upperPercentile-value"></span>
    </div>
  </div>
  <script>
    const deckgl = new deck.DeckGL({
      mapboxApiAccessToken: '<mapbox_pk_token>',
      mapStyle: 'mapbox://styles/mapbox/dark-v9',
      initialViewState: {
        longitude: -122.413756,
        latitude: 37.779528,
        zoom: 6,
        minZoom: 0,
        maxZoom: 21,
        pitch: 40.5
      },
      controller: true
    });

    //const data = d3.csv('https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv');

    const data = [
        {name: 'Colma1', passengers: 4214, lng: '-122.466233', lat: '37.684638'},
        {name: 'Colma2', passengers: 4214, lng: '-122.466233', lat: '37.684638'},
        {name: 'Colma3', passengers: 4214, lng: '-122.466233', lat: '37.684638'},
        {name: 'Civic Center1', passengers: 24798, lng: '-122.413756', lat: '37.779528'},
        {name: 'Civic Center2', passengers: 24798, lng: '-122.413756', lat: '37.779528'},
        {name: 'Civic Center3', passengers: 24798, lng: '-122.413756', lat: '37.779528'},
        {name: 'Civic Center4', passengers: 24798, lng: '-122.413756', lat: '37.779528'},
        {name: 'Civic Center5', passengers: 24798, lng: '-122.413756', lat: '37.779528'},
    ];

    const OPTIONS = ['radius', 'coverage', 'upperPercentile'];

    const COLOR_RANGE = [
      [1, 152, 189],
      [73, 227, 206],
      [216, 254, 181],
      [254, 237, 177],
      [254, 173, 84],
      [209, 55, 78]
    ];

    OPTIONS.forEach(key => {
      document.getElementById(key).oninput = renderLayer;
    });

    renderLayer();

    function renderLayer () {
      const options = {};
      OPTIONS.forEach(key => {
        const value = +document.getElementById(key).value;
        document.getElementById(key + '-value').innerHTML = value;
        options[key] = value;
      });

      const hexagonLayer = new deck.HexagonLayer({
        id: 'heatmap',
        colorRange: COLOR_RANGE,
        data,
        elevationRange: [0, 1000],
        elevationScale: 250,
        extruded: true,
        getPosition: d => [Number(d.lng), Number(d.lat)],
        opacity: 1,
        pickable: true,
        onHover: ({object, x, y}) => {
            const tooltip = `Count: 12`;
        },
        ...options
      });

      deckgl.setProps({
        layers: [hexagonLayer],
        tooltip: {
          'html': '<b>Elevation Value:</b>',
          'style': {
              'color': 'white'
          }
        }
      });
    }
  </script>
</body>
</html>

I would like to add a tooltip to each hexbin (bar chart on top of map), but I'm not sure how to accomplish this. The only examples I could find around tooltips was this, so it looks like it should be possible. I attempted to add it on the layer using this part of the code:

    tooltip: {
      'html': '<b>Elevation Value:</b>',
      'style': {
          'color': 'white'
      }
    }

but it did not work. Does anyone know how I can accomplish this? I have some extra data in the data field namely name and passengers, preferrably I would like to say create the first hexbin tooltip as a comma separated list of data.name values. The example seems to refer to variables using {colorValue} for example. Alternatively tooltips per hexbin could also possibly be acceptable. I'm just running on my local machine as a static page so not sure if that makes a difference.

Edit: Added the following code based on this, but this also did not work:

pickable: true,
onHover: ({object, x, y}) => {
  const tooltip = `Count: 12`;
},

It also referred to ${object.centroid.join(', ')}\nCount: ${object.points.length} but that gave an error.


Solution

  • The easiest way to do this is the getTooltip property. If you want to use the onHover property, which gives you a bit more control, you have to create and manage the tooltip DOM element yourself.