DEV Community
Follow
How a map works, Mercator, tiles, and your GPS pin
Interactive maps, like those in Google Maps, are built upon two fundamental mathematical concepts. The first is a method to project the Earth's spherical surface onto a flat screen. The second involves dividing this flat projection into a grid of smaller, manageable square tiles for efficient loading. Understanding these principles demystifies how map applications function and allows for precise location calculations.
The core challenge is reconciling the Earth's roundness with a flat display. This requires a map projection, a mathematical rule converting longitude and latitude into screen coordinates. Most web maps utilize the Web Mercator projection because it preserves angles and local shapes, ensuring directions remain consistent and north is always upward. However, this projection significantly distorts area, making polar regions disproportionately large.
The Mercator projection flattens the globe by directly mapping longitude to the x-axis. Latitude, however, is transformed using a logarithmic function that stretches areas near the poles more than those at the equator. This logarithmic transformation is the key to how the Mercator projection works. The resulting projected world is then divided into a quadtree structure of 256x256 pixel tiles.
These tiles are organized in a hierarchical system based on zoom levels, where each tile is identified by its zoom level and x, y coordinates. This tiling scheme allows maps to load only the necessary portions of the world, enabling smooth scrolling and interaction. A formula exists to convert a specific latitude and longitude into the exact tile it falls within.
The `asinh(tan(lat))` function represents the Mercator y-coordinate, normalized for the tile grid system. By truncating the fractional part of this calculation, one identifies the specific tile, while the fraction indicates the precise location within that tile. When a user drags a map, the application simply calculates which tiles are visible on screen and fetches them.
The blue dot representing a user's location is a direct result of this process. The device's GPS provides latitude and longitude, which are then projected using the same Mercator mathematics. The system determines the corresponding tiles and places the marker at the projected position on the screen. Understanding these underlying principles transforms opaque map interfaces into understandable systems.