Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active May 8, 2018 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrew-Reid/266edd7be65c59cd98c9cfaef9ccaba5 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/266edd7be65c59cd98c9cfaef9ccaba5 to your computer and use it in GitHub Desktop.
Leaflet and Popup with D3.js 2
<!DOCTYPE html>
<html>
<head>
<title>Leaflet with D3 popups</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="width: 960px; height: 500px;"></div>
<script>
var mymap = L.map('mapid').setView([51.5, -0.14], 14);
L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(mymap);
var popup = L.popup();
function click(e) {
var width = 200;
var height = 200;
var margin = {left: 10, top: 10, right: 6, bottom: 10};
var div = d3.create("div");
var svg = div.append("svg")
.attr("width",width+margin.left+margin.right)
.attr("height",height+margin.top+margin.bottom);
var g = svg.append("g")
.attr("transform","translate("+[margin.left,margin.top]+")");
var colors = d3.scaleLinear().domain([0,99]).range(["yellow","steelblue"]);
var rects = g.selectAll("rect")
.data(d3.range(100))
.enter()
.append("rect")
.attr("width", width/10 - 2)
.attr("height", height/10 - 2)
.attr("x", function(d,i) { return i%10 * width/10; })
.attr("y", function(d,i) { return Math.floor(i/10) * height/10; })
.attr("fill", function(d,i) { return colors(i); })
popup.setLatLng(e.latlng)
.setContent(div.node())
.openOn(mymap);
}
mymap.on('click', click);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment