An attempted mashup of D3 leaflet and color-scaled topojson
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<link href="//cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" rel="stylesheet">
<style>
html, body, #map {
display:block;
width:100%;
height:100%;
margin:0;
padding:0;
}
.states {
fill: none;
stroke: #fff;
stroke-linejoin: round;
}
.counties :hover {
fill: #0055ff !important;
stroke: #0022FF;
stroke-width:2.2px;
stroke-linejoin: round;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="//cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var map = new L.Map(document.querySelector('#map'), {
center: new L.LatLng(42, -98),
zoom: 5
});
var basemap = new L.tileLayer('//{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
maxZoom:18
}).addTo(map);
var fill = d3.scale.log()
.domain([10, 500])
.range(["yellow", "steelblue"]);
var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
console.log('svg added to leaflet');
d3.json("us.json", function(error, us) {
var bounds = d3.geo.bounds(topojson.feature(us, us.objects.counties));
var path = d3.geo.path().projection(project);
var feature = g.selectAll("path")
.data(us.objects.counties)
.enter().append("path");
var counties = topojson.feature(us, us.objects.counties).features;
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.attr("d", path)
.style("fill", function(d) { return fill(path.area(d)); });
map.on("viewreset", reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
var bottomLeft = project(bounds[0]),
topRight = project(bounds[1]);
svg .attr("width", topRight[0] - bottomLeft[0])
.attr("height", bottomLeft[1] - topRight[1])
.style("margin-left", bottomLeft[0] + "px")
.style("margin-top", topRight[1] + "px");
g .attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")");
feature.attr("d", path);
}
// Use Leaflet to implement a D3 geographic projection.
function project(x) {
var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
return [point.x, point.y];
}
});
</script>
</body>
</html>