This is in answer to this Stack Overflow question about how to place points on a map and how projections work.
forked from phil-pedruco's block: Plotting points on a map in D3
license: mit |
This is in answer to this Stack Overflow question about how to place points on a map and how projections work.
forked from phil-pedruco's block: Plotting points on a map in D3
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Point on a map D3</title> | |
<script src="http://d3js.org/d3.v4.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.geoMercator(); | |
// create path variable | |
var path = d3.geoPath() | |
.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> |