Skip to content

Instantly share code, notes, and snippets.

@phil-pedruco
Last active September 9, 2018 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save phil-pedruco/7745589 to your computer and use it in GitHub Desktop.
Save phil-pedruco/7745589 to your computer and use it in GitHub Desktop.
Plotting points on a map in D3

This is in answer to this Stack Overflow question about how to place points on a map and how projections work.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Point on a map D3</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<style type="text/css">
.feature {
fill: none;
stroke: grey;
stroke-width: 1px;
stroke-linejoin: round;
}
.mesh {
fill: none;
stroke: lightgrey;
stroke-width: 2px;
stroke-linejoin: round;
}
h1 {
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>Point in the north west part of SF</h1>
<script type="text/javascript">
var width = 950,
height = 550;
// set projection
var projection = d3.geo.mercator();
// create path variable
var path = d3.geo.path()
.projection(projection);
d3.json("us.json", function(error, topo) { console.log(topo);
states = topojson.feature(topo, topo.objects.states).features
// set projection parameters
projection
.scale(1000)
.center([-106, 37.5])
// create svg variable
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// points
aa = [-122.490402, 37.786453];
bb = [-122.389809, 37.72728];
console.log(projection(aa),projection(bb));
// add states from topojson
svg.selectAll("path")
.data(states).enter()
.append("path")
.attr("class", "feature")
.style("fill", "steelblue")
.attr("d", path);
// put boarder around states
svg.append("path")
.datum(topojson.mesh(topo, topo.objects.states, function(a, b) { return a !== b; }))
.attr("class", "mesh")
.attr("d", path);
// add circles to svg
svg.selectAll("circle")
.data([aa,bb]).enter()
.append("circle")
.attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; })
.attr("cy", function (d) { return projection(d)[1]; })
.attr("r", "8px")
.attr("fill", "red")
});
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@jhubley
Copy link

jhubley commented Dec 22, 2014

Hi there. I'm just getting started with D3, and I came across this example on bl.ocks.org. It's really helped me quickly understanding plotting. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment