Search code examples
javascriptd3.jsdatamaps

Datamap - retrieve country code based on given x and y coordinates


I'm making a visualization of a world map where i should be able to retrieve a country from a world map based on a given pair x and y pixel coordinates.

At the moment I'm using datamaps (http://datamaps.github.io/ ). But I can't find a way to retrieve a certain country name or id based on a given pair of x or y pixel coordinates. Can somebody guide me in the right direction?

Thanks in advance.


Solution

  • Well looking at the markup you can see that the 3 letter country code is added to the CSS class of each polygon:

    class="datamaps-subunit JPN"
    

    So what you need to do is find the polygon at the point you're interested in. This answer Hit-testing SVG shapes? might help you achieve that. It suggests things such as:

    svg.getIntersectionList(hitrect, null);
    

    or

    document.elementFromPoint(x, y);
    

    Once you've got that, it's relatively trivial to extract the class name:

    var code = d3.select(element).class().replace("datamaps-subunit ", "");