简体   繁体   中英

How to check if the mouse is inside actual map bounds in d3 geo?

I am trying to find if the mouse is inside the map bound in d3. I am using the map projection.invert(d3.mouse(container)) method to find it.

It is working if properly within the bound. But the problem is, when I am moving the mouse outside of the actual bound, it is still giving me some coordinates (lat-long).

I have made a demo in Observable.

Is there any way to know if I am moving the mouse outside of the map bounds?

You could just set a simple flag to make sure you are on a path:

d3.select(img).selectAll('path')
  .on("mouseover", function() { mutable isOn = true; })
  .on("mouseout", function() { mutable isOn = false; });

Or just change your mousemove to act on the paths instead of the svg:

d3.select(img).selectAll('path').on("mousemove", function() {
  mutable inverse = projection.invert(d3.mouse(this));
  mouse.attr("transform", `translate(${projection(mutable inverse)})`);
});

Updated observable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM