Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active September 25, 2019 03:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3indepth/c62b6ce6625b69f6007cea5fccdd4599 to your computer and use it in GitHub Desktop.
Save d3indepth/c62b6ce6625b69f6007cea5fccdd4599 to your computer and use it in GitHub Desktop.
D3 geo basic example (canvas)
license: gpl-3.0
height: 420
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Basic geo (canvas)</title>
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 14px;
color: #333;
}
#content .map path {
fill: #ddd;
stroke: #aaa;
}
</style>
<body>
<div id="content">
<canvas width="800" height="400"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Africa"
},
"geometry": {
"type": "Polygon",
"coordinates": [[[-6, 36], [33, 30], [43, 11], [51, 12], [29, -33], [18, -35], [7, 5], [-17, 14], [-6, 36]]]
}
},
{
"type": "Feature",
"properties": {
"name": "Australia"
},
"geometry": {
"type": "Polygon",
"coordinates": [[[143, -11], [153, -28], [144, -38], [131, -31], [116, -35], [114, -22], [136, -12], [140, -17], [143, -11]]]
}
},
{
"type": "Feature",
"properties": {
"name": "Timbuktu"
},
"geometry": {
"type": "Point",
"coordinates": [-3.0026, 16.7666]
}
}
]
};
var context = d3.select('#content canvas')
.node()
.getContext('2d');
var projection = d3.geoEquirectangular()
.scale(200)
.translate([200, 150]);
var geoGenerator = d3.geoPath()
.projection(projection)
.context(context);
function update(geojson) {
context.lineWidth = 0.5;
context.strokeStyle = '#aaa';
context.beginPath();
geoGenerator({type: 'FeatureCollection', features: geojson.features})
context.stroke();
}
update(geojson);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment