Leaflet d3.js Hexbin Demo

Demo of the hexbin plugin from the leaflet-d3 library

by tr00st

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://rawgit.com/d3/d3-plugins/master/hexbin/hexbin.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css">
<script src="https://rawgit.com/Asymmetrik/leaflet-d3/master/dist/leaflet-d3.js"></script>
<script src="https://rawgit.com/turban/d3.slider/master/d3.slider.js"></script>
<link rel="stylesheet" href="https://rawgit.com/turban/d3.slider/master/d3.slider.css">
<div id="map" style="width: 100%; height: 600px; border: 1px solid #ccc"></div>
<div id="slider"></div>

CSS

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

JavaScript

var center = [ 54.605160, -1.080250];
var randRadius = 0.5;
var numEntities = 10000;
var latFn = d3.random.normal(center[0], randRadius*0.5);
var longFn = d3.random.normal(center[1], randRadius);
var siltFn = d3.random.normal(0.5,0.2);

var map = L.map('map').setView(center, 11);
mapLink = 
    '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; ' + mapLink + ' Contributors',
        maxZoom: 18,
    }).addTo(map);

/* Initialize the SVG layer */
map._initPathRoot()    

/* Pick up the SVG from the map object */
var svg = d3.select("#map").select("svg"),
    g = svg.append("g");


// Create some objects
var collection = {"objects":[ ]};
for (var i = 0; i < numEntities; i++) {
    collection.objects.push({
        "entity":{
            "coordinates":[latFn(), longFn()],
            "siltLevel": siltFn()
        }
    });
}
var viewState = {
    slider: 1,
    colours: null
};

// Make a colour scale
var updateColours = function () {
    viewState.colours = d3.scale.linear()
        .domain([-0.1, viewState.slider*1.5,1.1])
        .range(["blue",'yellow',  "red"]);
}
updateColours();

/* Add a LatLng object to each item in the dataset */
collection.objects.forEach(function(d) {
    d.LatLng = new L.LatLng(d.entity.coordinates[0],
                            d.entity.coordinates[1]);
})

map.on("moveend", updateView);
updateView();


function updateView() {
    mapBounds = map.getBounds().pad(0.5);

    var feature = g.selectAll("circle")
        .data(collection.objects.filter(function (e, i, a) {
            
            return e.entity.siltLevel > viewState.slider && mapBounds.contains(e.LatLng);
        }));
    feature.enter()
        .append("circle")
        .style("stroke", "black")  
        .style("opacity", 1) 
        .attr("data-colour", function (e) {
            return e.Colour;
        })
        .attr("r", 5)
    ; 
    feature
       ...