Adding labels to points from a geojson
Last active
December 20, 2015 07:08
-
-
Save mapsam/6090678 to your computer and use it in GitHub Desktop.
D3: Geographic Point Labels
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
<!DOCTYPE html> | |
<meta http-equiv="content-type" content="text/html; charset=utf-8"> | |
<style> | |
.states { | |
fill: #e5e5e5; | |
stroke: #fff; | |
stroke-width:1px; | |
} | |
.cities { | |
fill:red; | |
} | |
.labels { | |
fill: #444; | |
font-family:arial; | |
font-size:0.7em; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://d3js.org/topojson.v1.min.js"></script> | |
<script src="http://d3js.org/queue.v1.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var svg = d3.select('body').append('svg') | |
.attr('width', width) | |
.attr('height', height); | |
var projection = d3.geo.albersUsa() | |
.scale(1000) | |
.translate([width / 2, height / 2]); | |
var path = d3.geo.path() | |
.projection(projection); | |
queue() | |
.defer(d3.json, '/svmatthews/raw/6090056/states.json') | |
.defer(d3.json, '/svmatthews/raw/6090056/cities.json') | |
.await(makeMyMap); | |
function makeMyMap(error, states, cities) { | |
svg.append('path') | |
.datum(topojson.feature(states, states.objects.usStates)) | |
.attr('d', path) | |
.attr('class', 'states'); | |
svg.selectAll('.cities') | |
.data(cities.features).enter().append('path') | |
.attr('d', path.pointRadius(4)) | |
.attr('class', 'cities'); | |
svg.selectAll('.labels') | |
.data(cities.features).enter().append('text') | |
.attr('transform', function(d) { | |
return 'translate(' + projection(d.geometry.coordinates) + ')'; | |
}) | |
.attr('dy', function(d){ | |
var city = d.properties.NAME | |
if (city == 'Washington') { | |
return 8; | |
} | |
else { | |
return -3; | |
} | |
}) // vertical offset | |
.attr('dx', 3) // horizontal offset | |
.text(function(d) { | |
return d.properties.NAME; | |
}) | |
.attr('class', 'labels'); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment