Demo of leaflet & D3 from Mike Bostock's tutorial, updated with an openstreetmap URL that works.
forked from pbogden's block: D3 + Leaflet
forked from brandonhaydu's block: D3 + Leaflet
forked from brandonhaydu's block: D3 + Leaflet v1
license: mit |
Demo of leaflet & D3 from Mike Bostock's tutorial, updated with an openstreetmap URL that works.
forked from pbogden's block: D3 + Leaflet
forked from brandonhaydu's block: D3 + Leaflet
forked from brandonhaydu's block: D3 + Leaflet v1
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>leaflet</title> | |
<style> | |
@import url(//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.css); | |
#map { | |
width: 960px; | |
height: 500px; | |
} | |
path { | |
fill: #000; | |
fill-opacity: .2; | |
stroke: #fff; | |
stroke-width: 1.5px; | |
} | |
path:hover { | |
fill: brown; | |
fill-opacity: .7; | |
} | |
</style> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.js"></script> | |
<body> | |
<div id="map"</div> | |
<script> | |
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', | |
osmAttrib = '© <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors', | |
osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}); | |
var map = L.map('map').setView([37.5, -115], 6).addLayer(osm); | |
var svgMap = d3.select(map.getPanes().overlayPane).append("svg"), | |
g = svgMap.append("g").attr("class", "leaflet-zoom-hide"); | |
var transform = d3.geo.transform({point: projectPoint}), | |
path = d3.geo.path().projection(transform); | |
d3.json("counties.json", function(error, ca) { | |
var features = ca.objects.CA.geometries.map(function(d) { return topojson.feature(ca, d); }); | |
var all = topojson.merge(ca, ca.objects.CA.geometries); | |
var states = g.selectAll("path") | |
.data(features) | |
.enter() | |
.append("path"); | |
map.on("viewreset", reset); | |
reset(); | |
// Reposition the SVG to cover the features. | |
function reset() { | |
var bounds = path.bounds(all), | |
topLeft = bounds[0], | |
bottomRight = bounds[1]; | |
svgMap .attr("width", bottomRight[0] - topLeft[0]) | |
.attr("height", bottomRight[1] - topLeft[1]) | |
.style("left", topLeft[0] + "px") | |
.style("top", topLeft[1] + "px"); | |
g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")"); | |
states.attr("d", path); | |
} | |
}); | |
// Use Leaflet to implement a D3 geometric transformation. | |
function projectPoint(x, y) { | |
// Returns the map layer point that corresponds to the given geographical coordinates | |
var point = map.latLngToLayerPoint(new L.LatLng(y, x)); | |
this.stream.point(point.x, point.y); | |
} | |
</script> |