Hex binning with Leaflet and turf.js
by Stefano
HTML
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="https://npmcdn.com/@turf/[email protected]/turf.min.js"></script>
<div id="map"></div>
CSS
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
border-radius: 5px;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
.legend .colorcircle {
border-radius: 50%;
width: 15px;
height: 15px;
margin-top: 0px;
}
JavaScript
/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////
// set center coordinates
var centerlat = 49.2837626;
var centerlon = -122.7932065;
// set default zoom level
var zoomLevel = 11;
// initialize map
var map = L.map('map').setView([centerlat, centerlon], zoomLevel);
// set source for map tiles
ATTR = '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a> | ' +
'© <a href="http://cartodb.com/attributions">CartoDB</a>';
CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
// add tiles to map
L.tileLayer(CDB_URL, {
attribution: ATTR
}).addTo(map);
/////////////////////////////////////////////////////////////////////////////////////////////
//generating the GeoJSON objects//
/////////////////////////////////////////////////////////////////////////////////////////////
//create some GeoJSON points to be sampled (function below)
var dotcount = 200;
var dots = make_dots(dotcount);
//parameters for hex grid
var bbox = [ -122.6248528, 49.3515919, -122.8933441, 49.218461 ];
var cellWidth = 0.3;
var units = 'miles';
//create hex grid and count points within each cell
var hexcounts = turf.hexGrid(bbox, cellWidth, units);
/**************************************************
REMOVED turf.count (not available in Turf v4.x)
and replaced with a loop to create properties
**************************************************/
// var hexcounts = turf.count(dots, hexgrid, 'pt_count');
hexcounts.features.forEach(function(hex) {
hex.properties = {pt_count: 0}
});
L.geoJson(hexcounts, {
onEachFeature: onEachHex
}).addTo(map);
function getRandomCoordinates(radius, uniform) {
var a = Math.random(),
b = Math.random();
// Flip for more uniformity.
if (uniform) {
if (b < a) {
...