Gary Frewin
Gary Frewin

Reputation: 565

Adding clicks to globe pins with html canvas and javascript

I'm trying to add some functionality to this spinning globe on codepen:

https://codepen.io/johan-tirholm/pen/JjoXJNg?editors=0110

I'd like to have a modal that pops up with details when you click on a pin.

This function draws the pin heads:

const drawMapPushPin = (ctx, pos, color) => {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(pos.x, pos.y, 20, 0, 2 * Math.PI);
ctx.fill();
}

I'm not familiar with how eventlisteners should be added here... How would I allow this push pin to be clicked and load a modal div?

Upvotes: 0

Views: 362

Answers (1)

Johan Tirholm
Johan Tirholm

Reputation: 36

You can do something like this:

const onClick = (event) => {
let offset = 50,
  rect = event.target.getBoundingClientRect(),
  clickPos = {
    x: event.clientX - rect.x,
    y: event.clientY - rect.y 
  }

  // Scale click to responsive canvas
  clickPos.x *= 1800 / rect.width;
  clickPos.y *= 1600 / rect.height;

  // Compare to existing markers
  for (const marker of markers) {
    let markerPos = latLongSphere(marker.lat + $.scroll.lat, marker.long + $.scroll.long, 630);

  // Make sure only frontside markers are clickable
  if(markerPos.z < 0) {
    continue;
  }

  if(Math.abs(clickPos.x - markerPos.x) < offset && Math.abs(clickPos.y -markerPos.y) < offset) {
   alert('clicked on marker: ' + marker.name);
   break;
  }
 }
}

https://codepen.io/johan-tirholm/pen/dbd53e20fe5bcf86ae69779b8cdc8ead

Good luck!

Upvotes: 2

Related Questions