Darrell Tufto
Darrell Tufto

Reputation: 41

Finding coordinates in d3 svg path

Please note before reading this: This is a project that I am doing for a class in university, if you know an answer; please only hint me in the right direction or show an example. For the same reason I will also not post the entirety of my code but I will describe my progress in detail.

For this project I created a map with d3. I am adding functionalities but after searching the internet for a few hours and trying some stuff, I couldn't find an answer to this problem:

To display extra information in a sidebar of the map, I need to check if coordinates in my data are in a given svg path. I can display coordinates on my map, using:

var coords = projection([longitude, latitude]);

After which I can use the array to display the coordinates in the correct area.

The paths are drawn like this:

svg.selectAll(".geodata")
  .data(geodata)
  .enter().append("path")

geodata is defined by:

var geodata = topojson.feature(data, data.objects.collection).features;

This is a topojson casted to a geojson. (It is stored as a topojson since those are smaller files and this will be used on a webapplication.)

However, I cannot check if certain coordinates are in a given path, here are the things I tried:

If you have an idea or know of an example, I would like to hear below. :)

Answers given:

Set the display to none and find your element below the elementByPoint:

console.log(this);
var element = document.elementFromPoint(coords[0], coords[1]);
console.log(element);
element.style.display = "none";

My comment: This doesn't work, it gives you a result within div-tags and not the corresponding path that you click (a county in this example).

Upvotes: 2

Views: 652

Answers (1)

Darrell Tufto
Darrell Tufto

Reputation: 41

As I cannot mark the question as answered in the comment section, I will copy the comment here and mark it as answered.

Using the svg path to see if a point is within a polygon assumes Cartesian coordinates - while d3 samples paths along great circle coordinates, the sampling rate may be coarse enough that a point falls outside of a the svg shape but within the geographic feature (it would appear on the border to us visually). Try d3.geoContains() with the original geographic data (if your original geographic data is spherical: latitude and longitude pairs) – Andrew Reid

Thanks a lot Andrew!

Edit: I now noticed that I can't set this as answered in the next 2 days so I will do that after.

Upvotes: 2

Related Questions