# 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));


var newX = (cursor.X * newZoomLevel) - mouseinWorld.X;

world = new Vector2(newX, newY)