var width = document.getElementById('map') .clientWidth; var height = document.getElementById('map') .clientHeight; var map = L.map('map', { center: [51.4659249585, -3.16769715331], zoom: 14 }); L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '© OpenStreetMap contributors, © CARTO' }) .addTo(map); var points = []; var draw = function() { d3.select('#overlay') .remove(); var bounds = map.getBounds(); var topLeft = map.latLngToLayerPoint(bounds.getNorthWest()); var bottomRight = map.latLngToLayerPoint(bounds.getSouthEast()); var existing = d3.set(); var drawLimit = bounds.pad(0.4); var voronoi = d3.voronoi() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .extent([ [topLeft.x, topLeft.y], [bottomRight.x, bottomRight.y] ]); var filteredPoints = points.filter(function(d) { var latlng = new L.LatLng(d.lat, d.lon); if (!drawLimit.contains(latlng)) { return false; } var point = map.latLngToLayerPoint(latlng); key = point.toString(); if (existing.has(key)) { return false; } existing.add(key); d.x = point.x; d.y = point.y; return true; }); var svg = d3.select(map.getPanes() .overlayPane) .append("svg") .attr('id', 'overlay') .attr("class", "leaflet-zoom-hide") .style("width", map.getSize() .x + 'px') .style("height", map.getSize() .y + 'px') .style("margin-left", topLeft.x + "px") .style("margin-top", topLeft.y + "px"); var g = svg.append("g") .attr("transform", "translate(" + (-topLeft.x) + "," + (-topLeft.y) + ")"); var buildPathFromPoint = function(d) { return d == null ? null : "M" + d.join("L") + "Z"; } var svgPoints = g.selectAll('g') .data(filteredPoints) .enter() .append("g") .attr("class", function(d) { return "point c" + d.count; }); svgPoints .exit() .remove(); svgPoints .append("path") .data(voronoi.polygons(filteredPoints)) .attr('class', 'point-cell') .attr("d", buildPathFromPoint); svgPoints .append("circle") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .style('fill', function(d) { return '#666'; }) .attr("r", 1); } d3.csv('postcode_data.csv', function(d) { return { postcode: d.postcode, lat: +d.lat, lon: +d.lon, count: +d.count }; }, function(error, rows) { points = rows; draw(); map.on('viewreset moveend', draw); });