Created
January 7, 2015 21:20
-
-
Save jamierob/a21843bf2b7f3eb54456 to your computer and use it in GitHub Desktop.
D3 leaflet apply class value from geojson data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- based off the code @ http://bost.ocks.org/mike/leaflet/ --> | |
<!DOCTYPE html> | |
<html class=""> | |
<meta charset="utf-8"> | |
<title>D3test</title> | |
<style> | |
@import url(//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.css); | |
html { height: 100% } | |
body { height: 100%; margin: 0; padding: 0;} | |
#map{ height: 100% } | |
svg { | |
position: relative; | |
} | |
path { | |
fill: #000; | |
fill-opacity: .2; | |
stroke: #fff; | |
stroke-width: 1.5px; | |
} | |
path:hover { | |
fill: brown; | |
fill-opacity: .7; | |
} | |
</style> | |
<header></header> | |
<div id="map"></div> | |
<footer></footer> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.js"></script> | |
<script> | |
var map = new L.Map("map", {center: [46.861967, -113.982825], zoom: 17}) | |
.addLayer(new L.TileLayer("http://tile1.map.umt.edu/tiles/tiles.py/composite/{z}/{x}/{y}.png")); | |
var svg = d3.select(map.getPanes().overlayPane).append("svg"), | |
g = svg.append("g").attr("class", "leaflet-zoom-hide"); | |
d3.json("bldgs.geojson", function (collection) { | |
var transform = d3.geo.transform({point: projectPoint}), | |
path = d3.geo.path().projection(transform); | |
var feature = g.selectAll("path") | |
.data(collection.features) | |
.enter() | |
.append("path"); | |
map.on("viewreset", reset); | |
reset(); | |
// Reposition the SVG to cover the features. | |
function reset() { | |
var bounds = path.bounds(collection), | |
topLeft = bounds[0], | |
bottomRight = bounds[1]; | |
svg.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] + ")"); | |
//apply a class with the 'handle' value from the geojson file | |
feature.attr("class", function (d) { | |
return "code " + d.handle; | |
}); | |
feature.attr("d", path); | |
} | |
// Use Leaflet to implement a D3 geometric transformation. | |
function projectPoint(x, y) { | |
var point = map.latLngToLayerPoint(new L.LatLng(y, x)); | |
this.stream.point(point.x, point.y); | |
} | |
}); | |
</script> | |
<script async src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment