blob: 15bb331e840b7756c536c239986c119bac403622 [file] [log] [blame]
Simon Huntbe245142015-06-11 17:32:10 -07001<!--
2 -- Sample code to show extracting country data from a countries TopoJSON
3 -- file and projecting it into an SVG layer.
4 --
5 -- See: http://bl.ocks.org/pnavarrc/62047b5638d624cfa9cb
6 -->
7<html>
8<head>
9 <title>S America</title>
10
11 <script charset="utf-8" src="../../tp/d3.min.js"></script>
12 <script charset="utf-8" src="../../tp/topojson.v1.min.js"></script>
13
14 <style>
15 svg {
16 border: 1px solid #888;
17 }
18 .country {
19 fill: #bcd1ff;
20 stroke: #7c79e6;
21 stroke-width: 1;
22 }
23 </style>
24</head>
25
26<body>
27 <div id="map"></div>
28
29 <script>
30 var datapath = '../../data/map/countries.topojson',
31 height = 500,
32 width = 500;
33
34 // create geographic projection
35 var projection = d3.geo.mercator()
36 .translate([width/2, height/2]);
37
38 // configure path generator
39 var pathGenerator = d3.geo.path()
40 .projection(projection);
41
42 var div = d3.select('#map'),
43 svg = div.append('svg'),
44 grp = svg.append('g');
45
46 svg.attr('width', width).attr('height', height);
47
48 d3.json(datapath, function (error, data) {
49 if (error) {
50 console.error(error);
51 throw error;
52 }
53
54 var features = topojson.feature(data, data.objects.countries).features;
55
56 // S.America
57 var southAmerica = features.filter(function (country) {
58 return country.properties.continent === 'South America';
59 });
60
61 var southAmericaFeature = {
62 type: 'FeatureCollection',
63 features: southAmerica
64 };
65
66 // compute bounds and centroid
67 var bounds = d3.geo.bounds(southAmericaFeature),
68 center = d3.geo.centroid(southAmericaFeature);
69
70 // compute angular distance between bound corners
71 var distance = d3.geo.distance(bounds[0], bounds[1]),
72 scale = height / distance / Math.sqrt(2);
73
74 // update projection
75 projection.scale(scale).center(center);
76
77 // draw
78 var countries = grp.selectAll('path.country')
79 .data([southAmericaFeature]);
80 countries.enter().append('path').classed('country', true);
81 countries.attr('d', pathGenerator);
82 countries.exit().remove();
83 });
84 </script>
85</body>
86
87</html>