Skip to content

Map

Purpose and Scope

This document details the Map class, which serves as the central orchestrator in OpenLayers that coordinates all mapping functionality. The Map class manages the rendering pipeline, integrates layers and data sources, handles user interactions, controls the tile loading system, and maintains the overall application state. For view state management, see View System. For layer architecture details, see Layer Architecture.

Overview

The Map class is the central orchestrator that coordinates all OpenLayers components into a cohesive mapping application. It manages the FrameState object that drives the rendering pipeline, coordinates the TileQueue for efficient data loading, and integrates Collection objects containing layers, controls, interactions, and overlays. The class extends BaseObject and provides the primary API for map manipulation and event handling.

Map Orchestration Architecture

SVG
100%

Map Class Structure

SVG
100%

Architecture

Map Class Diagram

SVG
100%

Constructor Options

The Map constructor accepts a MapOptions object with the following properties:

OptionTypeDescription
targetHTMLElement|stringThe DOM element or its ID where the map will be rendered
layersArray|Collection|LayerGroupThe layers to include in the map
viewView|PromiseThe view configuration for the map
controlsCollection|ArrayThe controls to add to the map (default: defaultControls())
interactionsCollection|ArrayThe interactions to add to the map (default: defaultInteractions())
overlaysCollection|ArrayThe overlays to add to the map
pixelRationumberThe device pixel ratio (default: DEVICE_PIXEL_RATIO)
moveTolerancenumberThe movement tolerance for click events (default: 1)
keyboardEventTargetHTMLElement|Document|stringThe element to listen for keyboard events
maxTilesLoadingnumberMaximum number of tiles to load simultaneously (default: 16)

The constructor processes these options through createOptionsInternal() and initializes the map's internal state, including the TileQueue, viewport DOM structure, and event handlers.

Initialization

To create a new map instance, you need to provide configuration options including target element, view, and layers. The following shows the typical initialization pattern:

const map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new OSM()
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

DOM Structure and Viewport Management

The Map class creates a hierarchical DOM structure that manages rendering layers, overlays, and controls. This structure is dynamically created and inserted into the target element.

Map DOM Hierarchy

SVG
100%

The DOM structure creation process:

  1. viewport creation: src/ol/Map.js369-375

    • CSS class includes touch detection: 'ol-viewport' + ('ontouchstart' in window ? ' ol-touch' : '')
    • Positioned relatively with hidden overflow
  2. overlayContainer setup: src/ol/Map.js381-388

    • Absolutely positioned, full size
    • pointerEvents: 'none' to allow map interaction
  3. overlayContainerStopEvent setup: src/ol/Map.js394-401

    • Similar to overlayContainer_ but stops event propagation
    • Used for controls and blocking overlays

Access methods:

Sources: src/ol/Map.js369-401 src/ol/Map.js1059-1083

Rendering Pipeline and FrameState Management

The Map class orchestrates a sophisticated rendering pipeline centered around the FrameState object, which contains all information needed for a single render frame.

Rendering Flow

SVG
100%

FrameState Object Structure

The FrameState typedef defines the complete rendering context:

PropertyTypePurpose
pixelRationumberDevice pixel ratio for high-DPI displays
timenumberTimestamp when rendering was requested
viewStateViewStateCurrent view center, zoom, rotation, projection
layerStatesArrayLayerState[]Computed state for all layers
tileQueueTileQueueTile loading priority queue
coordinateToPixelTransformTransformMap coordinates to pixel transformation
pixelToCoordinateTransformTransformPixel to map coordinates transformation
extentExtentCurrent visible extent in view projection
sizeSizeMap size in pixels
declutterObjectDecluttering trees for overlapping features

The rendering process:

  1. Frame Scheduling: render() uses requestAnimationFrame for smooth animation src/ol/Map.js1486-1490
  2. State Creation: renderFrame_() builds the FrameState with current map state src/ol/Map.js1549-1655
  3. Renderer Execution: The renderer_ processes the frame state and renders all layers
  4. Post-Processing: Handles tile loading, events, and frame scheduling

Core Components Management

View Management

The Map manages a View object that controls the center, zoom level, rotation, and projection of the map. The view can be set during initialization or later using setView().

// Set a new view
map.setView(new View({
  center: [0, 0],
  zoom: 2
}));

// Get the current view
const view = map.getView();

When the view changes, the map updates its rendering to reflect the new view state.

Layer Management

The Map manages layers through a LayerGroup. Layers can be added, removed, or modified using the following methods:

// Add a new layer
map.addLayer(newLayer);

// Remove a layer
map.removeLayer(existingLayer);

// Clear and set new layers
map.setLayers([layer1, layer2]);

// Get all layers
const layers = map.getLayers();

Controls and Interactions

The Map manages collections of controls and interactions:

// Add a control
map.addControl(new ZoomControl());

// Add an interaction
map.addInteraction(new DragRotate());

// Remove a control
map.removeControl(control);

// Remove an interaction
map.removeInteraction(interaction);

The map properly sets up event listeners for these components and ensures they are correctly wired to the map.

Rendering Process

Rendering Flow

SVG
100%

The rendering process starts with the render() method, which schedules a new frame to be rendered at the next animation frame. The actual rendering happens in renderFrame_(), which:

  1. Creates a FrameState object with the current map state
  2. Passes the frame state to the renderer
  3. Handles post-render functions
  4. Dispatches map events like movestart, moveend, etc.

The FrameState object contains all information needed for rendering, including the view state, layer states, and transformations.

Event Handling

Map Browser Events

The Map class handles browser events through the MapBrowserEventHandler class. Events are processed and dispatched as MapBrowserEvent instances.

SVG
100%

The map first dispatches events to its own listeners, then to all active interactions in reverse order of their addition.

Feature Detection

The Map provides methods to detect features at a given pixel:

// Check if there's a feature at a pixel
const hasFeature = map.hasFeatureAtPixel(pixel, options);

// Get all features at a pixel
const features = map.getFeaturesAtPixel(pixel, options);

// Execute a callback for each feature at a pixel
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
  // Do something with the feature
}, options);

These methods are useful for implementing feature selection and interaction.

Common Operations

Coordinate Transformations and Event Handling

The Map class provides coordinate transformation capabilities and comprehensive event processing for user interactions.

Coordinate Transformation Methods

// Convert from pixel to coordinate (user projection)
const coordinate = map.getCoordinateFromPixel(pixel);

// Convert from coordinate to pixel
const pixel = map.getPixelFromCoordinate(coordinate);

// Get coordinate from mouse/touch event
const eventCoord = map.getEventCoordinate(event);

// Internal methods (view projection)
const viewCoord = map.getCoordinateFromPixelInternal(pixel);
const viewPixel = map.getPixelFromCoordinateInternal(coordinate);

The coordinate transformation system uses the FrameState transforms:

  • coordinateToPixelTransform: Converts map coordinates to screen pixels
  • pixelToCoordinateTransform: Converts screen pixels to map coordinates

These transforms are updated each frame and account for the current view state (center, zoom, rotation).

Event Processing Pipeline

SVG
100%

The event system processes MapBrowserEvent objects that include:

  • Pixel coordinates relative to the map viewport
  • Map coordinates in both user and view projections
  • Original DOM event reference
  • Event type and modifiers

Size Management

The Map automatically handles size changes of its container, but you can also force a size update:

// Force update of map size
map.updateSize();

Component Integration and Lifecycle Management

The Map class serves as the integration point for all OpenLayers components, managing their lifecycle and coordinating their interactions.

Component Integration Architecture

SVG
100%

Component Lifecycle Management

The Map class manages component lifecycle through event-driven patterns:

  1. Collection Event Handling: src/ol/Map.js508-590

    • Collection.ADD events automatically call setMap(this) on new components
    • Collection.REMOVE events call setMap(null) to clean up references
  2. Layer Integration: src/ol/Map.js177-188

    • setLayerMapProperty() recursively sets map references on layers and layer groups
    • removeLayerMapProperty() cleans up map references when layers are removed
  3. View State Synchronization: src/ol/Map.js493-494

    • handleViewChanged_() responds to view property changes
    • Automatically triggers rendering when view state changes
  4. Cleanup and Disposal: src/ol/Map.js662-669

    • disposeInternal() properly cleans up all collections and DOM elements
    • Disconnects ResizeObserver and removes event listeners

The integration ensures that all components maintain proper references to their parent map and receive necessary lifecycle events for initialization and cleanup.

Summary

The Map class is the core component of OpenLayers that brings together all other components to create interactive maps. It manages the rendering process, handles user interactions, and provides an API for manipulating the map state. Understanding the Map class is essential for working with OpenLayers effectively.