# Using the mouse position to zoom in on a map

**URL:** <https://discourse.processing.org/t/using-the-mouse-position-to-zoom-in-on-a-map/44137>\
**Category:** Coding Questions\
**Created:** [March 21, 2024, 9:47pm UTC](https://discourse.processing.org/t/using-the-mouse-position-to-zoom-in-on-a-map/44137 "2024-03-21T21:47:13Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![scudly](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/scudly/32/5597_2.png) [@scudly](https://discourse.processing.org/u/scudly)\
**Post date:** [March 22, 2024, 6:12pm UTC](https://discourse.processing.org/t/using-the-mouse-position-to-zoom-in-on-a-map/44137/10 "2024-03-22T18:12:28Z")

</div>

`camX` and `camY` should be `float`s, not `int`s.

`draw()` should not translate by the mouse position. Instead, when you change the scale, you need to change `camX` and `camY` so that they move relative to the world-space position of the mouse.

I simplified `draw()` and updated `mouseWheel()` to make the changes:

```auto
int gridSize = 20;
float camX = 0;
float camY = 0;
float camScale = 1;
boolean w = false, a = false, s = false, d = false;

void setup() {
  size(800, 800);
}

void draw() {
  if(w) {camY -= 5;}
  if(s) {camY += 5;}
  if(a) {camX -= 5;}
  if(d) {camX += 5;}
    
  background(220);
  
  push();
  scale(camScale);
  translate(-camX, -camY);
  drawGrid();
  pop();
}

void drawGrid() {
  for(int i = 0; i < 50; i++) {
    for(int j = 0; j < 50; j++) {
      fill(255);
      square(i*gridSize, j*gridSize, gridSize);
    }
  }
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  if(e == 1) {e = 1/1.1;}
  if(e == -1) {e = 1.1;}
  float oldScale = camScale;
  if(camScale * e >= 0.2) {
    camScale *= e;
  } else {
    camScale = 0.2;
  }
  float worldX = camX + mouseX/oldScale;
  camX = worldX - mouseX/camScale;
  float worldY = camY + mouseY/oldScale;
  camY = worldY - mouseY/camScale;
}

void keyPressed() {
  if (key == 'w') {w = true;}
  if (key == 's') {s = true;}
  if (key == 'a') {a = true;}
  if (key == 'd') {d = true;}
}

void keyReleased() {
  if (key == 'w') {w = false;}
  if (key == 's') {s = false;}
  if (key == 'a') {a = false;}
  if (key == 'd') {d = false;}
}

```

---

_[View the full topic](https://discourse.processing.org/t/using-the-mouse-position-to-zoom-in-on-a-map/44137)._
