d3.geoContains example.
From D3 in Depth book by Peter Cook.
| license: gpl-3.0 | |
| height: 430 | |
| border: no |
d3.geoContains example.
From D3 in Depth book by Peter Cook.
| <!DOCTYPE html> | |
| <meta charset="utf-8"> | |
| <head> | |
| <title>Geo contains</title> | |
| </head> | |
| <style> | |
| body { | |
| font-family: "Helvetica Neue", Helvetica, sans-serif; | |
| font-size: 14px; | |
| color: #333; | |
| } | |
| </style> | |
| <body> | |
| <div id="content"> | |
| <div>Click an area to highlight</div> | |
| <canvas width="800" height="400"></canvas> | |
| </div> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script> | |
| <script> | |
| var geojson = {} | |
| var context = d3.select('#content canvas') | |
| .node() | |
| .getContext('2d'); | |
| var projection = d3.geoOrthographic() | |
| .scale(300) | |
| .rotate([30, -45]); | |
| var geoGenerator = d3.geoPath() | |
| .projection(projection) | |
| .context(context); | |
| var state = { | |
| clickedLocation: null | |
| } | |
| function handleClick() { | |
| var pos = d3.mouse(this) | |
| state.clickedLocation = projection.invert(pos) | |
| update() | |
| } | |
| function initialise() { | |
| d3.select('canvas') | |
| .on('click', handleClick); | |
| } | |
| function update() { | |
| context.clearRect(0, 0, 800, 400); | |
| geojson.features.forEach(function(d) { | |
| context.beginPath(); | |
| context.fillStyle = state.clickedLocation && d3.geoContains(d, state.clickedLocation) ? 'red' : '#aaa'; | |
| geoGenerator(d); | |
| context.fill(); | |
| }) | |
| } | |
| // REQUEST DATA | |
| d3.json('https://gist.githubusercontent.com/d3indepth/f28e1c3a99ea6d84986f35ac8646fac7/raw/c58cede8dab4673c91a3db702d50f7447b373d98/ne_110m_land.json', function(err, json) { | |
| geojson = json; | |
| initialise(); | |
| update(); | |
| }) | |
| </script> | |
| </body> | |
| </html> |