Frontend System Design24 min readPremium

Design Google Maps – Frontend System Design

55. Design Google Maps

We’ll walk through the frontend system design for the Google Maps web client: a map of the whole planet that pans at 60fps, zooms from continents to doorsteps, keeps street labels readable while you rotate it, and shows search results, place details, and driving routes on top. You’ll see how the Web Mercator projection turns the planet into a pyramid of square tiles, why modern maps ship vector tiles and draw them with WebGL, how a tile pipeline fetches, cancels, and decodes in workers, and how labels and thousands of markers stay legible.

This is not the Figma question, even though both use tiles. Figma tiles a design canvas that users edit. A map tiles read-only geographic data that someone else produced, so the hard parts move to projection math, network scheduling, label collision, and point density. It is also not Uber, where the interesting part is live driver tracking on top of a map you take for granted. Here, the map is the product.

Problem Statement

Design the frontend for a web mapping application like Google Maps.

Requirements:

  • A world map with smooth pan, zoom (world to street level), rotation, and tilt
  • Readable labels for roads, places, and points of interest at every zoom
  • A search box with autocomplete, biased to where the user is looking
  • Search results and points of interest as markers, even when there are thousands
  • A place details panel and turn-by-turn directions drawn as a route on the map
  • Shareable URLs that restore the exact view

Describe the client architecture, how map data reaches the screen, and how the app stays fast on slow networks and slow devices.

Interviewers are checking three things. Do you know how a sphere becomes square tiles, and can you compute which tiles are on screen? Can you design a loading pipeline that survives a fast fling without flooding the network? And do you know what happens to labels and markers when there are far more of them than pixels?


Clarifying Questions

# Question Interviewer’s Answer
1 Do we own the map data and tile servers, or consume a third-party API? We own them. Focus on the client and the contract with the tile CDN.
2 Raster images or vector data? Your call. Justify it.
3 Do we need rotation and 3D tilt? Rotation and tilt, yes. Full 3D buildings and Street View are out of scope.
4 How many markers can a search return? A search shows up to 20 results, but a “show all restaurants” layer can have tens of thousands of points.
5 Live navigation with rerouting? No. Show a route and its steps. Turn-by-turn guidance is a mobile app feature.
6 Which devices and networks? Desktop and mobile browsers. Assume some users on slow 3G and low-end Android phones.

Question 2 is the big fork, and the interviewer wants you to pick. Question 3 settles it: rotation and tilt with readable labels rule out pre-rendered images. Question 4 tells you markers need clustering, not just a for loop of DOM nodes. Question 6 means you budget CPU and bytes, not just pixels.


Requirements

Functional

  • Pan by drag, fling with inertia, zoom with wheel, trackpad pinch, touch pinch, double-click, and keyboard.
  • Rotate and tilt with right-drag, two-finger twist, or modifier keys. Labels stay upright.
  • Search with autocomplete. Selecting a result flies the camera there and opens the place panel.
  • Show category layers (restaurants, gas stations) with thousands of points, clustered when zoomed out.
  • Directions between two places with driving, walking, and transit options. Draw the route and fit the camera to it.
  • “My location” with an accuracy circle.
  • Every view is a URL: center, zoom, open place, and route.

Non-Functional

  • 60fps during pan and zoom. Input to visible movement within one frame.
  • First useful map in under 2 seconds on a mid-range phone on 4G.
  • Never show a blank grey area while zooming. Show something lower resolution instead.
  • Bounded memory: a cap on cached tiles and GPU buffers, with eviction.
  • Network politeness: no more requests than the viewport needs, and cancel what is no longer needed.
  • Usable with a keyboard and a screen reader, with a list alternative to the map.

The phrase “never show a blank area” decides a lot. It forces you to keep lower-zoom tiles around as placeholders, to prioritize the center of the screen, and to fade new tiles in rather than pop them.

Napkin Math

Metric Estimate Calculation So what?
Tiles in the whole world at z = 20 ~1.1 trillion 4^20 = 1,099,511,627,776 The client only ever knows the few dozen around it.
256 px tiles on a 1920 × 1080 viewport 32 to 54 1920 / 256 = 7.5 and 1080 / 256 ≈ 4.2; with partial edges up to 9 × 6 One screen is about 50 requests if nothing is cached.
512 px vector tiles on the same viewport up to 20 1920 / 512 = 3.75, 1080 / 512 ≈ 2.1; up to 5 × 4 Bigger tiles mean fewer requests per screen.
Bytes per screen ~1 MB 54 × ~20 KB raster, or 20 × ~50 KB gzipped vector Similar on first load. Vector wins on zoom, DPR 2, and restyles.
Requests per pan ~6 per 256 px One new column of tiles. A 2,000 px fling crosses ~8 columns ≈ 48 tiles Most fling tiles are off-screen before they arrive. Cancel them.
GPU memory for a cached raster tile 256 KB 256 × 256 × 4 bytes; 200 tiles ≈ 50 MB Cap the cache by bytes, not by count.
Markers for a dense category 10,000 points One DOM node each, versus ~100 clusters at city zoom Cluster, and draw on the GPU.

The fling row is the one interviewers like. A user flicks the map, the client requests 48 tiles in the first frames, and by the time the responses arrive the camera is somewhere else. Without cancellation you spend the user’s bandwidth on tiles nobody will see, and the tiles they do need wait behind them.


Architecture

Google Maps web client architecture: React UI shell, map engine on the main thread, worker pool, and backend services

The client has four layers. The key boundary is between the React panels and the map engine: the camera changes every frame, so it never goes through React state.

Layer Owns Runs on Talks to
UI Shell Search, place panel, directions, URL React, main thread Places and Directions APIs, map engine commands
Map Engine Camera, gestures, tile set, labels, markers Main thread, WebGL Workers, tile cache
Worker Pool Fetch, protobuf decode, styling, tessellation, cluster index Web Workers Tile CDN, style service
Services Tiles, styles, glyphs, places, routes CDN and APIs Everything above over HTTP/2

The map engine exposes a small imperative API: flyTo, fitBounds, setLayerData, on("moveend"). React calls it from effects and subscribes to coarse events. That is the same shape as the public Maps JavaScript API and open-source engines like MapLibre GL JS, which is a good sign you’ve drawn the line in the right place.

“React renders the panels. The map engine owns the camera and runs its own frame loop. React hears about the map only on moveend, never on every frame of a pan.”

Workers are not optional. Decoding a vector tile and turning its polygons into triangles takes several milliseconds per tile. Twenty tiles on the main thread is a dropped frame for every tile that lands.


Data Model

Google Maps client data model: camera, tile, feature layer, feature, style layer, place, and route

There are two stores with very different lifetimes. Map data is a cache of tiles keyed by z/x/y, evicted freely. App data (places, routes, search results) is a normalized store that React reads.


type LngLat = { readonly lng: number; readonly lat: number };

type TileId = { readonly z: number; readonly x: number; readonly y: number }; // keyed as "z/x/y"

type TileState =
  | { kind: "loading" }
  | { kind: "ready"; buckets: GpuBuckets; bytes: number }
  | { kind: "error"; retryAt: number };

interface Camera {
  center: LngLat;
  zoom: number;      // fractional, e.g. 14.3
  bearing: number;   // degrees clockwise from north
  pitch: number;     // degrees of tilt, capped (e.g. 0 to 60)
}

interface StyleLayer {
  id: string;
  sourceLayer: string;                       // which FeatureLayer it draws
  type: "fill" | "line" | "symbol";
  filter?: unknown[];                        // expression, e.g. ["==", ["get", "class"], "motorway"]
  minzoom?: number;
  maxzoom?: number;
  paint: Record<string, unknown>;           // colors, widths, opacity
  layout: Record<string, unknown>;          // text field, font, placement
}

interface FeatureLayer {
  name: string;      // "road", "water", "poi"
  extent: number;    // tile-local integer grid, usually 4096
  features: Feature[];
}

interface Feature {
  id?: number;
  type: "Point" | "LineString" | "Polygon";
  geometry: Int16Array;                              // tile-local coordinates
  props: Record<string, string | number | boolean>;  // class, name, rank
}

interface Place {
  placeId: string;
  name: string;
  location: LngLat;
  category: string;
  rating?: number;
  openNow?: boolean;
}

interface Route {
  id: string;
  mode: "driving" | "walking" | "transit";
  polyline: string;          // encoded polyline
  distanceMeters: number;
  durationSec: number;
  bounds: { sw: LngLat; ne: LngLat };
}

Three choices are worth defending.

The tile is the unit of everything. You fetch a tile, decode a tile, cache a tile, and evict a tile. Features never live outside their tile, so eviction is one Map.delete plus freeing its GPU buffers.

Tile-local integer coordinates. Inside a vector tile, geometry is integers from 0 to the extent (4096 by default in the Mapbox Vector Tile spec). That keeps payloads small and dodges Float32 precision loss on the GPU at street level, because every tile is drawn relative to its own origin.

The camera is not React state. It changes 60 times a second during a pan. Putting it in a store would re-render every subscriber on every frame. The engine owns it and publishes a throttled copy on moveend.


Projection and the Tile Pyramid

Tile pyramid from zoom 0 to zoom 3 with the San Francisco tile highlighted, plus the lng/lat to tile formulas and ground resolution per zoom

Web Mercator maps longitude linearly to x and stretches latitude so that the world becomes a square. The square needs a cut-off, so latitudes beyond about ±85.0511° are dropped. That is why the poles are missing on most web maps.

At zoom 0 the whole square is one 256 × 256 tile. Each zoom level splits every tile into four, so at zoom z there are 2^z × 2^z tiles and the world is 256 × 2^z pixels wide. Ground resolution halves with each level: about 156,543 meters per pixel at zoom 0 on the equator, 4.78 m/px at zoom 15, multiplied by cos(latitude) away from the equator.

Tile y counts down from the north edge. Older TMS tile schemes count up from the south, so upside-down tiles usually mean a y flip. The quadtree relationship is just bit shifts: a tile’s parent is (z - 1, x >> 1, y >> 1) and its four children are (z + 1, 2x + {0,1}, 2y + {0,1}).

To find the visible tiles, convert the camera center to fractional tile coordinates, expand by half the viewport in tile units, and enumerate the rectangle. Fractional zoom means you pick an integer tile zoom and draw those tiles scaled by 2^(zoom – z), so a 256 px tile shows at between 256 and 512 CSS pixels.

Put this in a pure projection module with two functions.

  • LngLat to tile. Clamp latitude to ±85.0511°, map longitude linearly to x, apply the Mercator formula to y, and scale both by 2^z. The result is fractional. Flooring it gives the tile index, and the fraction is the position inside the tile. San Francisco (-122.4194, 37.7749) at z14 lands at about x 2620.56, y 6332.76, so tile 14/2620/6332.
  • Visible tiles. Pick the integer zoom, compute how many CSS pixels one tile occupies at the fractional zoom, and enumerate the tile rectangle around the center that covers half the viewport in each direction. Clamp y to the world. Wrap x modulo 2^z so the world repeats horizontally, and keep the wrap count so the renderer offsets each copy. Sort by distance from the center, so the scheduler requests the middle of the screen first.

Both functions are pure and cheap, so they run on every camera change with no caching.

That enumeration ignores rotation and tilt. With a bearing, compute the four screen corners in world space and cover their bounding quad. With tilt, the far edge of the screen covers far more ground, so use lower zoom tiles toward the horizon. Otherwise a 60° tilt asks for hundreds of tiny tiles nobody can read.


Rendering: Raster vs Vector Tiles

The oldest web maps were grids of 256 px PNG images in absolutely positioned <img> tags. That still works, and it is a fine answer for a simple store locator. It falls apart on the requirements we just agreed to.

Aspect Raster tiles (PNG/WebP) Vector tiles (protobuf + WebGL)
Rotation and tilt Labels rotate with the image and turn upside down Labels are placed per frame and stay upright
Fractional zoom Blurry between levels Crisp at any scale
High-DPI screens Need a separate @2x tile set (4× pixels) Same data, drawn at device resolution
Restyle (dark mode, traffic, hide POIs) New tile set from the server Change the style on the client
Overzoom Pixelated past the last level A z14 tile can be drawn sharply at z18 and beyond
Client cost Almost none Decode, tessellate, shaders, text rendering

Pick vector tiles and say what they cost. Google moved its own web map to vector rendering with WebGL in its 2013 redesign, and the Maps JavaScript API’s “vector map” type is the one that supports tilt and rotation. Mapbox GL JS and MapLibre GL JS work the same way.

What a vector tile contains

The open, widely used format is the Mapbox Vector Tile (MVT) spec. A tile is a Protocol Buffers message containing named layers. Each layer has features with a geometry type (point, line, polygon), a geometry encoded as compact commands (MoveTo, LineTo, ClosePath) with zigzag-encoded integer deltas, and properties stored as indexes into per-layer key and value tables. Repeated strings like "class": "primary" are stored once per layer.

The tile has no colors or line widths. A style document maps layers to drawing rules: “draw road features where class == motorway as a 6 px orange line from zoom 6, widening by zoom.” Change the style and the same bytes become dark mode, a transit map, or a map with POIs hidden.

From bytes to triangles

  1. Decode the protobuf in a worker into layers and features.
  2. Filter and style: evaluate each style layer’s filter at this zoom and compute paint values.
  3. Tessellate: polygons become triangles (an ear-clipping triangulator is the usual choice), lines become triangle strips with joins and caps, and labels become glyph quads.
  4. Bucket geometry by style layer into typed arrays: one vertex buffer and index buffer per bucket.
  5. Transfer the ArrayBuffers to the main thread with postMessage(msg, transferList). Transfer moves ownership with no copy.
  6. Upload on the main thread: one bufferData per bucket. Drawing a tile is then a handful of draw calls in style-layer order.

Text is the hard part. WebGL has no text API. A common approach is signed distance field (SDF) glyphs: the server ships glyph atlases per font and Unicode range, and the shader renders crisp text at any size and rotation, with halos for contrast. Right-to-left and complex scripts need shaping, which is why many engines load a shaping plugin lazily only when such text appears.


Tile Loading Pipeline

Sequence diagram of a pan: camera update, visible tile computation, cache hits and misses, worker fetch and decode, abort of off-screen tiles

The pipeline runs on every camera change. It is a small scheduler, and getting its priorities right is most of the perceived speed of the map.

  1. Compute the wanted set for the new camera, sorted by distance from the center.
  2. Cache hits draw this frame.
  3. Misses get a placeholder: the nearest cached ancestor, scaled up. Zooming out, cached children can cover a missing parent instead.
  4. Request misses in priority order through the worker pool, with a cap on in-flight requests.
  5. Cancel any in-flight request whose tile is no longer wanted.
  6. On arrival, upload buffers, fade the tile in over ~150ms on top of its placeholder, and re-run label placement.

The worker side is a small request loop with cancellation built in.


type ToWorker =
  | { type: "load"; key: string; priority: "high" | "low" }
  | { type: "cancel"; key: string };

Each worker keeps a map from tile key to an AbortController.

  • Load fetches the tile URL with the data version and a Fetch Priority hint, decodes the protobuf, and builds buckets with the current style. It transfers the bucket buffers back in a loaded message.
  • Cancel aborts the fetch and removes the entry. If the cancel arrives while decoding, the worker checks the abort signal before posting and silently drops the result.
  • Errors post a failed message, unless the request was cancelled. The main thread marks the tile with a retry time instead of retrying in a tight loop.

On the main thread, the cache is an LRU keyed by tile key and capped by bytes. A JavaScript Map iterates in insertion order, so re-inserting on access is a complete LRU in a few lines. Tiles that are visible right now are pinned so eviction never removes something on screen.


interface ReadyTile { bytes: number; dispose(): void }

The tile cache has three operations. get returns a tile and marks it most recently used. peek returns a tile without touching recency, which the placeholder search uses so a probe doesn’t keep stale ancestors alive. set adds a tile, then walks from the oldest entry, evicting and disposing unpinned tiles (deleting their GL buffers) until the byte total is under budget.

The placeholder search is a short walk up the quadtree. For a missing tile, check its parent, grandparent, and so on up to about five levels, and return the first one in the cache along with its scale factor (2 per level).

Three details separate a strong answer here.

  • Keep the parents warm. When the camera is at z14, also keep z13 and z12 tiles for the area. They are a quarter and a sixteenth of the count, and they are what makes a zoom-out instant.
  • Cap in-flight requests. HTTP/2 multiplexes many requests on one connection, so you no longer need the old a.tile, b.tile, c.tile subdomains that worked around the six-connections-per-host limit of HTTP/1.1. You still cap at roughly 16 to 32 in flight, so the center tiles are not queued behind the edges.
  • Debounce requests during a fling, not rendering. Rendering continues every frame from the cache and placeholders. New requests are issued once the camera slows, or for the predicted landing area of the fling.

Tiles are immutable for a given data version, so serve them with a long Cache-Control: max-age and a version in the URL. The browser HTTP cache then gives you a free second-level cache across sessions. Traffic overlays are the exception: they change every minute or two, so they live in a separate source with a short max-age.


Pan, Zoom, and Gestures

Store the camera center in normalized Mercator units (0 to 1 across the world), so a pan is just center -= delta / (256 × 2^zoom). Zoom toward the cursor by keeping the world point under the pointer fixed: convert the pointer to world coordinates, change the zoom, convert again, and shift the center by the difference.

Pointer Events, pinch, and inertia

Use Pointer Events for mouse, pen, and touch with one code path. Set touch-action: none on the map so the browser doesn’t scroll or zoom the page, and call setPointerCapture so a drag that leaves the map still ends cleanly. Track active pointers in a Map. One pointer pans. Two pointers pinch: the change in distance is the zoom delta, and the movement of their midpoint is the pan.

A gesture controller owns this and talks to the camera only through panBy and zoomAround.

  • One pointer pans by the movement delta and records a timestamped sample, keeping only the last 100ms.
  • Two pointers pan by the movement of their midpoint and zoom by the log2 of the change in distance between them, anchored on the midpoint.
  • Release with one pointer starts a fling. Velocity is the displacement across the sample window divided by its duration. Each animation frame pans by velocity times elapsed time, then multiplies velocity by an exponential decay (about e^(-0.004 × dt)). The fling stops when speed drops below a small threshold.

Every handler ends by requesting a render, which coalesces into one frame.

Measure velocity over the last ~100ms, not the last event. A finger that pauses before lifting should not fling. A pointerdown during a fling cancels it with cancelAnimationFrame, which is how users “catch” the map. With a decay constant of 0.004 per ms, a 2 px/ms flick glides about 500 px, which is in the range users expect.

Wheel normalization

Wheel input is messy. WheelEvent.deltaMode can be pixels (0), lines (1), or pages (2), and a mouse wheel notch and a trackpad swipe produce very different magnitudes. In Chromium and Firefox, a trackpad pinch arrives as a wheel event with ctrlKey set. Safari also exposes its own non-standard gesturestart and gesturechange events.

Normalization is one pure function from a WheelEvent to a zoom delta. Convert the delta to pixels first: lines become about 16 px each, and pages become the map’s height. Then scale it. Use a much higher rate when ctrlKey is set, because pinch deltas are small. Clamp the result to at most one zoom level per event. The listener must be registered with passive: false so it can call preventDefault. Otherwise the browser zooms the whole page.

Animate a mouse wheel notch over ~200ms to the next level. Apply trackpad deltas directly, because the hardware already sends smooth input. Telling them apart is a heuristic, so keep it in one function you can tune.


Labels and Collision

Collision grid with placed, rejected, and fading labels, and the per-frame placement loop with a collision check and fade

A city tile can contain thousands of candidate labels: street names, shops, neighborhoods, transit stops. You can show maybe a hundred without overlap. Deciding which ones is called symbol placement, and with rotation and tilt it has to be redone as the camera moves, not baked into the tile.

  1. Collect symbols from all visible tiles. Deduplicate labels that cross tile edges (the same road name appears in both tiles).
  2. Sort by priority: a style-assigned rank (cities before neighborhoods, highways before alleys), then labels that were visible last frame, so the map doesn’t flicker.
  3. For each symbol, project its anchor to the screen and compute its box: text plus icon plus padding.
  4. Check the box against a grid index of already placed boxes. If it hits, hide it. If not, insert it and show it.
  5. Animate opacity toward the new target over ~300ms in the shader, so labels fade instead of popping.

The collision grid divides the screen into cells of about 64 px. Each cell holds the boxes that overlap it. Placing a label computes which cells its box covers, tests the box against every box already in those cells, and either rejects it or inserts it into all of them. The grid is rebuilt from scratch on each placement pass, because the camera has moved and every projected box has changed.

A uniform grid works because label boxes are small and similar in size. Each check touches a handful of cells, so placing a few thousand candidates costs well under a few milliseconds. Run placement every few frames (or on a time budget) rather than every frame during a pan, and let the opacity animation hide the lag. Labels along curved roads are the harder case: they are placed as a chain of small boxes along the line, and rejected if the curve is too sharp for the text.

Markers at scale

Twenty search results are fine as DOM elements: they get hover states, focus, and accessible names for free. Ten thousand restaurants are not. That is ten thousand absolutely positioned nodes repositioned on every frame of a pan.

Approach Good for Breaks at
DOM markers Under ~100 interactive pins Layout and style cost per node during pan
WebGL symbol layer Thousands of icons in one draw call You build hit testing and focus yourself
Clustering + either Tens of thousands to millions of points Needs an index rebuilt when data changes

Clustering groups points that would overlap at the current zoom into one circle with a count. The standard open-source library is Mapbox’s supercluster: it builds a KD-tree per zoom level, greedily merging points within a pixel radius from the max zoom upward. On moveend you call getClusters([west, south, east, north], zoom), and on a cluster click getClusterExpansionZoom(id) tells you how far to zoom to split it.

Run the index in a worker. Building it for a large dataset takes long enough to drop frames, and query results are small. Draw clusters and unclustered points in the WebGL symbol layer, and promote only the selected or hovered marker to a DOM element so it can hold focus and a tooltip. Keeping a results list in sync with the map bounds is covered in the Airbnb question.


Search, Place Details, and Directions

Autocomplete with location bias

“Blue Bottle” should mean the coffee shop near the map, not the one in Tokyo. Send the camera’s center and visible radius as a location bias with each request. Google’s Places API exposes this as locationBias, and it is a bias, not a filter: a strong match elsewhere still appears.

  • Debounce keystrokes by ~150 to 250ms, and abort the previous request with AbortController so a slow early response can’t overwrite a newer one.
  • Cache results by (query, rounded location) so backspacing is instant.
  • Group requests from one search into a session token, from the first keystroke to the selected place. Google’s Places API bills an autocomplete session this way, which rewards you for the debounce.
  • Use the ARIA combobox pattern: role="combobox" on the <input>, role="listbox" for suggestions, aria-activedescendant for the highlighted row.

A general autocomplete deep dive covers the rest. The map-specific parts are the location bias and what happens on select: fetch place details, flyTo the location, and open the panel, in parallel.

Place panel

The panel is ordinary React. Render the name and address from the autocomplete result immediately, then fill in hours, photos, and reviews when details arrive. Request only the fields you render: the Places API takes a field mask, and details are priced by field group.

Route polyline

A driving route can have thousands of points. As JSON numbers that is tens of kilobytes. The encoded polyline format compresses it into a short ASCII string: coordinates are multiplied by 1e5 and rounded, each value stored as a delta from the previous point, zigzag-encoded so negatives are small, and split into 5-bit chunks offset by 63 into printable characters.

The decoder is a small pure function in the directions module. It reads characters one at a time, subtracts 63, and accumulates 5-bit chunks until a chunk without the continuation bit ends the value. It undoes the zigzag encoding to recover the signed delta and adds that to a running latitude or longitude, alternating between the two. Each finished pair is divided by 10precision (1e5 by default). The reference string _p~iF~ps|U_ulLnnqC_mqNvxq`@ decodes to (38.5, -120.2), (40.7, -120.95), (43.252, -126.453), which makes a good unit test.

Draw the decoded route as a WebGL line layer above roads and below labels, with a wider casing line underneath for contrast. Simplify it per zoom (Douglas-Peucker with a tolerance of about one pixel) so a cross-country route at zoom 5 isn’t thousands of invisible segments. Then call fitBounds(route.bounds, { padding }), with padding that accounts for the directions panel covering the left side of the map.


State and Data Flow

Think of it as three loops running at different speeds.

  • Frame loop (60Hz). Gestures mutate the camera, the engine computes visible tiles, draws from cache and placeholders, and requests misses. React is not involved.
  • Settle loop (on moveend). The engine publishes the camera. React updates the URL, re-queries the cluster worker for the new bounds, and refreshes “search this area” results.
  • User loop. A search selection or a directions request updates the app store. Effects call engine commands like flyTo and setLayerData.

URL as state

Google Maps encodes the view in the path, like /maps/@37.7749,-122.4194,14z, with a place or route segment in front when one is open. Do the same. Parse it on load so a shared link restores the exact view without a geolocation prompt.

  • Update the camera part with history.replaceState on moveend, never per frame. Safari throws if a page calls the history API more than about 100 times in 30 seconds.
  • Use history.pushState when the user opens a place or a route, so the back button closes the panel instead of leaving the site.
  • Round coordinates to the precision the zoom needs. Seven decimals at zoom 3 is noise in a shared link.

Geolocation

Call navigator.geolocation.watchPosition only after the user clicks “my location”. A permission prompt on page load gets denied and is hard to recover from. The API needs a secure context (HTTPS). Draw the blue dot with a circle whose radius is coords.accuracy meters converted to pixels at the current latitude and zoom. Handle PERMISSION_DENIED with a message that tells the user how to re-enable it, and use navigator.permissions.query({ name: "geolocation" }) to show the right button state up front.


API

Map data is static files on a CDN. App features are REST. The “realtime” channel in a map client is the message protocol between the main thread and the workers, and it deserves types like any network API.


// Static, cacheable (CDN)
GET /styles/:styleId.json                       // sources, layers, glyph and sprite URLs, version
GET /tiles/:z/:x/:y.pbf?v=:dataVersion          // Cache-Control: public, max-age=31536000
GET /glyphs/:fontstack/:range.pbf               // SDF glyphs, e.g. 0-255.pbf
GET /traffic/:z/:x/:y.pbf                       // Cache-Control: max-age=60

// App (REST)
GET  /api/places/autocomplete?q=blue%20bot&lat=37.77&lng=-122.42&radius=5000&session=:token
GET  /api/places/:placeId?fields=name,rating,hours,photos&session=:token
GET  /api/places/search?category=restaurant&bbox=-122.52,37.70,-122.35,37.83&cursor=:c
POST /api/directions   { origin: LngLat | placeId, destination: LngLat | placeId, mode, departAt? }
//   -> { routes: Route[] }  each with an encoded polyline, legs, steps, bounds

// Main thread <-> tile workers
type ToWorker =
  | { type: "setStyle"; style: StyleSpec }
  | { type: "load"; key: string; priority: "high" | "low" }
  | { type: "cancel"; key: string };

type FromWorker =
  | { type: "loaded"; key: string; buckets: SerializedBuckets; symbols: SymbolCandidate[] }
  | { type: "failed"; key: string; error: string };

Version tiles by data version in the URL, not by a short max-age. Then every tile can be cached for a year, and a data release is a new style document that points to the new version. The bbox search endpoint takes a cursor because a dense area can return far more results than one response should carry.


Optimizations

Problem Technique Effect
Blank areas while zooming Draw cached parents or children as placeholders Something is always on screen
Wasted requests during a fling AbortController per tile, request on settle Bandwidth goes to tiles that will be seen
Decode jank Worker pool, transferable buffers Main thread only uploads and draws
Slow first paint Preload the style and center tiles from the URL Tile requests start before the engine boots
Too many tiles when tilted Lower zoom toward the horizon Bounded tile count at any pitch
Label flicker Prefer last frame’s labels, fade opacity Stable, calm labels during pan
10,000 markers Clustering in a worker, WebGL symbols ~100 drawn items, one draw call
Heavy JavaScript bundle Lazy-load directions, street imagery, RTL shaping Map visible before panels hydrate

For the first load, the server knows the camera from the URL. Inline the style and emit <link rel="preload"> hints for the center tiles, so the browser starts fetching them while the map bundle is still downloading. That alone takes a round trip off the first useful paint.


Handling Edge Cases

  • The antimeridian. Panning east past 180° must keep going. Wrap tile x with modulo and draw world copies with an offset. Route and bounds math must handle a box whose west edge is greater than its east edge.
  • The poles. Mercator cannot show them. Clamp latitude to ±85.0511° and clamp the camera so you can’t pan into empty space.
  • WebGL unavailable or context lost. Listen for webglcontextlost and webglcontextrestored, and rebuild GPU buffers from cached decoded tiles. Where WebGL is missing, fall back to raster tiles in <img> elements. Google Maps shipped a similar fallback, called Lite mode, for browsers without WebGL.
  • Slow or metered networks. When navigator.connection.saveData is set (Chromium only), skip prefetch rings, request fewer zoom levels, and lower the in-flight cap. On a failed tile, retry with exponential backoff and keep showing the placeholder.
  • Offline. Downloadable offline areas are a mobile app feature. On the web, a Service Worker can serve recently viewed tiles from Cache Storage and show a clear “offline” banner. Search and directions fail gracefully with a retry.
  • Background tabs. requestAnimationFrame stops in hidden tabs. Pause watchPosition and traffic refresh on visibilitychange, then resume.

Accessibility and Security

Accessibility

A WebGL canvas is one image to a screen reader. You can’t make every street accessible, but you can make every task possible without the map.

  • The map container is focusable with a label. Arrow keys pan, + and - zoom, and the shortcuts are listed in a help dialog. The Maps JavaScript API ships this same keyboard behaviour.
  • Search results also render as a real list next to the map. That list is the accessible way to browse results, and each row focuses the matching marker.
  • Announce camera and result changes in an aria-live="polite" region: “Showing 20 coffee shops near Mission District”. Never announce every frame of a pan.
  • Directions steps are an ordered list with distances in text, not only a line on the map.
  • Respect prefers-reduced-motion: replace flyTo arcs with a jump, and shorten label fades.

Security and abuse

  • A browser API key is public by definition. Restrict it by HTTP referrer to your domains and by API, so a copied key fails on someone else’s site. Google Maps Platform keys support both restrictions.
  • Set per-key and per-user quotas on the expensive APIs (autocomplete, details, directions), and rate limit by IP at the edge. Scrapers go after place data, not tiles.
  • Place names, reviews, and user-contributed text are untrusted. Render them as text in React, never as HTML.
  • Location is sensitive. Don’t send precise coordinates to analytics, round them before logging, and only request geolocation after a user gesture.

What a Strong Answer Sounds Like

Topic Junior answer Senior answer
Map data “Load map images” Web Mercator z/x/y pyramid, vector tiles styled on the client
Loading Fetch every visible tile Center-first priority, cancel on pan, LRU by bytes, parent placeholders
Performance “Use a fast library” Decode and tessellate in workers, transfer buffers, camera outside React
Labels Draw all of them Priority-ordered placement with a collision grid and fades
Markers One DOM node per result Cluster index in a worker, GPU symbols, DOM only for focus
Search Call the API on each key Debounce, abort stale requests, location bias, session tokens

Conclusion: How to Design Google Maps

Start with the projection. Web Mercator turns the planet into a square, and the square becomes a pyramid of 2^z × 2^z tiles addressed by z/x/y. Everything else is about getting the right tiles to the screen fast: compute the visible set, fetch center-first, cancel what scrolls away, decode in workers, and always draw a parent tile while the children load.

Then pick vector tiles and own their cost. They give you rotation, tilt, crisp labels at any zoom, and restyling without new data, in exchange for a WebGL renderer, a text pipeline, and per-frame label collision. Add clustering for dense points, location-biased autocomplete, an encoded polyline for routes, and a URL that restores the view. If you can explain the fling math and why cancelled tile requests matter, you’ve shown the interviewer you understand how a real map client stays fast.