Skip to content

Map

Map is the core class of maptalks. It creates and manages a map on a given HTML container, handling the spatial reference (projection), view state (center/zoom/pitch/bearing), layer management, interaction (drag/zoom/rotate/pitch), coordinate conversion, and the event system.

The inheritance chain is Map → Handlerable(Eventable(Renderable(Class))), so a Map has event (on/off/once/fire), configuration (config), rendering (getRendererClass) and interaction-handler capabilities.

js
import { Map, TileLayer } from "maptalks";

const map = new Map("map", {
  center: [121.47, 31.23],
  zoom: 14,
  baseLayer: new TileLayer("base", {
    urlTemplate: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
    subdomains: ["a", "b", "c", "d"],
  }),
});

Constructor

js
new Map(container, options)

Parameters:

  • container String | HTMLElement The map container — a DOM element or its id.
  • options Object required. Common construction options:
OptionTypeDescription
centerNumber[] | Coordinaterequired initial map center
zoomNumberrequired initial zoom level
spatialReferenceObjectspatial reference, default EPSG:3857
baseLayerLayerinitial base layer
layersLayer[]other initial layers
pitchNumberinitial pitch (degrees)
bearingNumberinitial bearing (degrees)

Options

View & zoom

OptionTypeDescriptionDefault
centerCrossBooleanShow a red cross at map centerfalse
seamlessZoomBooleanUse seamless zoom modetrue
zoomAnimationBooleanEnable zoom animationtrue
zoomAnimationDurationNumberZoom animation duration (ms)330
panAnimationBooleanContinue pan animation after drag/touchtrue
panAnimationDurationNumberPan animation duration (ms)600
rotateAnimationBooleanContinue rotation animationtrue
rotateAnimationDurationNumberRotation animation duration (ms)800
maxZoomNumberMaximum zoom levelnull
minZoomNumberMinimum zoom levelnull
maxExtentExtentMaximum extent restrictionnull
maxPitchNumberMaximum pitch80
maxVisualPitchNumberMaximum visual pitch70

Interaction

OptionTypeDescriptionDefault
draggableBooleanEnable dragtrue
dragPanBooleanDrag to pantrue
dragRotateBooleanRight-click or Ctrl+left-click drag to rotatetrue
dragPitchBooleanRight-click or Ctrl+left-click drag to pitchtrue
switchDragButtonBooleanSwitch left button to rotate, right to movefalse
zoomableBooleanEnable zoomtrue
scrollWheelZoomBooleanScroll-wheel zoomtrue
doubleClickZoomBooleanDouble-click zoomtrue
touchGestureBooleanAllow two-finger touch zoom/rotate/pitchtrue
touchZoomBooleanTouch zoomtrue
touchRotateBooleanTouch rotatetrue
touchPitchBooleanTouch pitchtrue
boxZoomBooleanBox zoomfalse

Rendering & performance

OptionTypeDescriptionDefault
rendererString | String[]Renderer type (canvas / gl / gpu, see the note below)['canvas','gl','gpu']
devicePixelRatioNumberOverride device DPRnull
hitDetectBooleanLayer hit detection for cursor styletrue
hitDetectLimitNumberMax layers to hit-detect5
fpsOnInteractingNumberFPS while interacting, 0 to disable25
stopRenderOnOffscreenBooleanStop rendering when container is offscreentrue
fogBooleanDraw fog in the distancetrue
fogColorNumber[]Fog color [r,g,b][233,233,233]
cameraFarUndergroundInMeterNumberCamera far distance underground (m)2000

The map uses the first available renderer in the renderer list, in order. The default ['canvas','gl','gpu'] prefers 2D canvas rendering; pass 'gpu' explicitly to force WebGPU rendering (MapGPURenderer).

  • 'canvas' — 2D canvas rendering, the default path for 2D layers (tiles, markers, etc.).
  • 'gl' — WebGL rendering (MapGLRenderer), the path for 3D scenes.
  • 'gpu' — WebGPU rendering (MapGPURenderer), registered via Map.registerRenderer('gpu', MapGPURenderer); it creates the context with canvas.getContext('webgpu') and uses reshader.GraphicsDevice as the GPU device (isWebGPU() returns true).

WebGPU rendering notes (see WebGPU rendering):

  • Browser/device requirement: requires a WebGPU-capable browser (modern Chromium such as desktop Chrome/Edge, and newer Safari and Firefox) and a WebGPU-capable GPU/driver; check navigator.gpu to detect support.
  • Screenshot & export: WebGPU does not preserve the drawing buffer by default, so toDataURL()/screenshot relies on the preserveGpuDrawingBuffer option; when enabled, each frame is read back into a readback canvas (device.preserveDrawingBuffer).

Controls

OptionTypeDescriptionDefault
controlBooleanAllow adding controlstrue
attributionBoolean | ObjectShow attribution controltrue
zoomControlBoolean | ObjectZoom controlfalse
scaleControlBoolean | ObjectScale controlfalse
overviewControlBoolean | ObjectOverview controlfalse

Member Methods

Lifecycle & basics

  • isLoaded(): boolean — whether the map is loaded
  • getContainer(): HTMLElement — get the map container
  • getSize(): Size — get the map pixel size
  • remove(): Map — remove the map
  • isRemoved(): boolean — whether the map is removed
  • checkSize(force?): Map — check and update container size
  • setDevicePixelRatio(dpr): Map / getDevicePixelRatio(): number — set/get DPR
  • toJSON(options?): Object — export a map JSON snapshot
  • getRenderer() — get the renderer instance

View & camera

  • getZoom(): number / setZoom(zoom, options?): Map — get/set zoom
  • zoomIn(): Map / zoomOut(): Map — zoom in/out one level
  • getCenter(): Coordinate / setCenter(center, padding?): Map — get/set center
  • setCenterAndZoom(center, zoom?, padding?): Map — set center and zoom together
  • getView(): MapViewType / setView(view): Map — get/set view (center/zoom/pitch/bearing)
  • getPitch(): number / setPitch(pitch): Map — get/set pitch
  • getBearing(): number / setBearing(bearing): Map — get/set bearing
  • getFov(): number / setFov(fov): Map — get/set FOV
  • getResolution(zoom?): number — get resolution
  • setCameraPosition(coordinate): Map — set camera from a coordinate
  • setCameraMovements(frameOptions, option?): Map — run sequential camera frames (auto flight)
  • lookAt(params): Map — point the camera at a coordinate
  • isZooming(): boolean — whether zooming
  • isAnimating(): boolean — whether animating

Pan & animation

  • panTo(coordinate, options?, step?): Map — smoothly pan to a target
  • panBy(offset, options?, step?): Map — pan by pixel offset
  • animateTo(view, options?, step?): Player — animate the view
  • flyTo(view, options?, step?): this — smoothly fly to a view
  • isRotating(): boolean / isMoving(): boolean — rotation/movement state

Layer management

  • getBaseLayer(): Layer / setBaseLayer(baseLayer): Map — get/set base layer
  • removeBaseLayer(): Map — remove the base layer
  • getLayers(filter?): Layer[] — get layers
  • getLayer(id): Layer | null — get a layer by id
  • addLayer(layers, ...otherLayers): this — add layers
  • removeLayer(layers): this — remove layers
  • sortLayers(layers): Map — sort layers

Spatial reference & extent

  • getSpatialReference() / setSpatialReference(ref): Map — get/set spatial reference
  • getProjection() — get projection
  • getFullExtent(): Extent — get full extent
  • getMaxExtent(): Extent / setMaxExtent(extent): Map — get/set max extent

Coordinate conversion

  • coordinateToPoint(coordinate, zoom?, out?): Point — coordinate to 2D point
  • pointToCoordinate(point, zoom?, out?): Coordinate — 2D point to coordinate
  • coordinateToContainerPoint(coordinate, zoom?, out?): Point — coordinate to container point
  • containerPointToCoordinate(containerPoint, out?): Coordinate — container point to coordinate
  • getExtent(): Extent — get the current view geographic extent
  • getContainerExtent(): PointExtent — get the container extent

Distance & measurement

  • distanceToPixel(xDist, yDist, zoom?): Size — geographic distance to pixels
  • pixelToDistance(width, height): number — pixels to geographic distance
  • computeLength(coord1, coord2): number — distance between two coordinates (m)
  • computeGeometryLength(geometry): number — geometry length (m)
  • computeGeometryArea(geometry): number — geometry area (sq m)

Query & identify

  • identify(opts, callback): Map — identify geometry at a coordinate
  • identifyAtPoint(point, opts, callback): Map — identify geometry at a container point
  • getCollisionIndex(): CollisionIndex — get the collision index

View history

  • getViewHistory(): MapViewType[] — get view history
  • hasPreviousView(): boolean / hasNextView(): boolean — has previous/next view
  • zoomToPreviousView(options?): MapViewType / zoomToNextView(options?): MapViewType — go to previous/next view

Export & fullscreen

  • toDataURL(options?): string | null — export an image
  • isFullScreen(): boolean — whether fullscreen
  • requestFullScreen(dom?): Map — request fullscreen
  • cancelFullScreen(): Map — cancel fullscreen

Static Methods

  • Map.VERSION — version number
  • Map.fromJSON(container, profile, options?): Map — rebuild a map from JSON
  • Map.addOnLoadHook(fn, ...args): Map — add a hook after map load

Events

View & interaction

EventFired when
movestart / moving / moveendpan starts/ongoing/ends
zoomstart / zooming / zoomendzoom starts/ongoing/ends
rotatestart / rotate / rotateendbearing changes
pitchstart / pitch / pitchendpitch changes
dragrotatestart / dragrotating / dragrotateenddrag-rotate
fovchangeFOV changes
resizecontainer resize
viewchangeview changes

Layers

EventFired when
addlayerlayer added
removelayerlayer removed
setbaselayerbase layer set
baselayerchangestart / baselayerload / baselayerchangeendbase layer changes

Animation

EventFired when
animatestart / animating / animateendanimation
animateinterruptedanimation interrupted

Lifecycle

EventFired when
removestart / removeendmap removed
fullscreenstart / fullscreenend / cancelfullscreenfullscreen
js
map.on("zoomend", (e) => {
  console.log("zoom:", map.getZoom(), "center:", map.getCenter());
});