Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3js: how to get Lat/Log geocoordinates from mouse click?

Using some D3js code and projected topojson data on a map dataviz of any projection, how can I get back geocoordinates ? Something such:

var svg = d3.select("#viz").append("svg:svg")
 .attr("width", 320)
 .attr("height", 200)
 .on("mousedown", mousedown)
 .on("click", mouselocation);

How to get the geocordinates from a click on a D3js map visualisation ?

Links to demos welcome.


Edit: a list of relevant demos :

  • OpenLayers demo... but we what D3js.
  • Jason Davies/rotate/ use of projection.invert(d3.mouse(this))
like image 903
khinester Avatar asked Jun 04 '12 16:06

khinester


1 Answers

Use d3.mouse to get the pixel coordinates, and then use the projection (d3.geo.azimuthal, here) to invert x and y to longitude and latitude. For example:

d3.select("svg").on("mousedown.log", function() {
  console.log(projection.invert(d3.mouse(this)));
});

If you want to support clicking on the background of the SVG, you may also want an invisible rect with pointer-events: all. (Also note: older versions of D3 used d3.svg.mouse rather than d3.mouse.)

like image 117
mbostock Avatar answered Nov 08 '22 22:11

mbostock