# zoom to cursor calculation

I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.

so far, all I have is the resizing but I now need to change the map position.

What I have: map x and y; map width and height; cursor x and y.

Any help would be most welcome.

-

Assuming that your map x and map y mean the top left corner of the screen area over your map in map coordinates and map width and map height are the dimensions of your map at the actual zoom level again in map coordinates (not screen coordinates), first, calculate your zoom ratio:

``````zoom x = screen width / map width;
``````

Let's assume the aspect ratio does not change: zoom x = zoom y = zoom; If you want to change the zoom to next zoom, first find the coords of the new screen over your map:

``````new map width = screen width / next zoom

new map height = screen height / next zoom
``````

We need to find the change in both values and distribute these depending on the mouse position on the screen. If the mouse position would be in the exact center screen position, then this change would be evenly divided between the top-bottom and left-right sides. Since the mouse is at an arbitrary position, we need to find the ratios for the height and width changes for the sides.

Let's assume that the screen dimensions are screen max width and screen max height; The new coordinates of your screen (dimensions new map width, new map height) over your map are:

``````new map x = map x - (cursor x / screen max width * (new map width - map width))
new map y = map y - (cursor y / screen max height * (new map height - map height))
``````

To convert any map coordinate to a screen coordinate:

``````screen x = map x * zoom
``````

and to convert back:

``````map x = screen x / zoom
``````
-

Or for people using XNA when the system is flipped.

First calculate the mouse cursor in the world. Since the mouse position system in XNA is flipped subtract the mouse Y from the height of the screen.

``````var mouseinWorld = new Vector2(
(cursor.X * oldZoomLevel) - world.X,
((cursor.Y - screen.Height) * oldZoomLevel) + world.Y));
``````

Next is to calculate the new world location.

``````var newX = (cursor.X * newZoomLevel) - mouseinWorld.X;
var newY = mouseinWorld.Y - ((cursor.Y - screen.Height) * newZoomLevel)
``````

Now update the world location with the newly calculated coordinates.

``````world = new Vector2(newX, newY)
``````
-