Leaflet d3.js Hexbin Demo

Demo of the hexbin plugin from the leaflet-d3 library

by Ryan

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css">
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<script src="https://unpkg.com/@asymmetrik/leaflet-d3@4/dist/leaflet-d3.js" charset="utf-8"></script>

<div id="map" style="width: 600px; height: 400px; border: 1px solid #ccc"></div>
<button onclick="generateData()">Generate Data</button>

CSS

.hexbin-hexagon {
    stroke: #000;
    stroke-width: 1px;
}

JavaScript

var center = [39.4, -78];

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib});

map = new L.Map('map', {layers: [osm], center: new L.LatLng(center[0], center[1]), zoom: 7});

var options = {
    radius : 12,
    opacity: 0.5,
    duration: 500
};

var hexLayer = L.hexbinLayer(options).addTo(map)
hexLayer.colorScale().range(['white', 'blue']);

hexLayer
  .radiusRange([6, 11])
	.lng(function(d) { return d[0]; })
  .lat(function(d) { return d[1]; })
  .colorValue(function(d) { return d.length; })
  .radiusValue(function(d) { return d.length; });

var latFn = d3.randomNormal(center[0], 1);
var longFn = d3.randomNormal(center[1], 1);

var generateData = function(){
    var data = [];
    for(i=0; i<1000; i++){
        data.push([longFn(),  latFn()]);
    }
    hexLayer.data(data);
};

generateData();