Central map creation, styling, data management, and rendering capabilities. The Map class is the primary interface for all mapping operations and extends the Camera class to provide view management.
The main Map class that creates and manages a Mapbox GL map instance.
/**
* Creates a new Map instance
* @param options - Configuration options for the map
*/
class Map extends Camera {
constructor(options: MapOptions);
// Source management
addSource(id: string, source: SourceSpecification): Map;
getSource(id: string): Source | undefined;
removeSource(id: string): Map;
// Layer management
addLayer(layer: LayerSpecification, beforeId?: string): Map;
getLayer(id: string): Layer | undefined;
removeLayer(id: string): Map;
moveLayer(id: string, beforeId?: string): Map;
// Style management
setStyle(style: StyleSpecification | string, options?: StyleSetterOptions): Map;
getStyle(): StyleSpecification;
// Feature querying
queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: QueryRenderedFeaturesParams): MapboxGeoJSONFeature[];
querySourceFeatures(sourceId: string, options?: QuerySourceFeaturesParams): MapboxGeoJSONFeature[];
// Control management
addControl(control: IControl, position?: ControlPosition): Map;
removeControl(control: IControl): Map;
// Coordinate projection
project(lnglat: LngLatLike, altitude?: number): Point;
unproject(point: PointLike, altitude?: number): LngLat;
// State management
loaded(): boolean;
resize(): Map;
remove(): void;
// Image management
addImage(id: string, image: HTMLImageElement | ImageBitmap | ImageData | { width: number; height: number; data: Uint8Array | Uint8ClampedArray }, options?: { pixelRatio?: number; sdf?: boolean }): Map;
removeImage(id: string): Map;
hasImage(id: string): boolean;
// Feature state
setFeatureState(feature: FeatureSelector, state: FeatureState): Map;
getFeatureState(feature: FeatureSelector): FeatureState;
removeFeatureState(feature: FeatureSelector, key?: string): Map;
}
interface MapOptions {
// Required
container: string | HTMLElement;
// Initial view
style?: StyleSpecification | string;
center?: LngLatLike;
zoom?: number;
bearing?: number;
pitch?: number;
bounds?: LngLatBoundsLike;
fitBoundsOptions?: FitBoundsOptions;
// Interaction options
interactive?: boolean;
scrollZoom?: boolean | ScrollZoomHandlerOptions;
boxZoom?: boolean;
dragRotate?: boolean;
dragPan?: boolean | DragPanOptions;
keyboard?: boolean;
doubleClickZoom?: boolean;
touchPitch?: boolean | TouchPitchHandlerOptions;
touchZoomRotate?: boolean | TouchZoomRotateHandlerOptions;
// Display options
minZoom?: number;
maxZoom?: number;
minPitch?: number;
maxPitch?: number;
maxBounds?: LngLatBoundsLike;
// Rendering options
hash?: boolean;
attributionControl?: boolean;
customAttribution?: string | string[];
logoPosition?: ControlPosition;
failIfMajorPerformanceCaveat?: boolean;
preserveDrawingBuffer?: boolean;
antialias?: boolean;
refreshExpiredTiles?: boolean;
maxTileCacheSize?: number;
localIdeographFontFamily?: string;
transformRequest?: RequestTransformFunction;
collectResourceTiming?: boolean;
fadeDuration?: number;
crossSourceCollisions?: boolean;
// 3D and projection options
projection?: ProjectionSpecification;
renderWorldCopies?: boolean;
worldview?: string;
// Cooperative gestures
cooperativeGestures?: boolean;
}Usage Examples:
import mapboxgl from 'mapbox-gl';
// Basic map creation
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-74.006, 40.7128],
zoom: 9
});
// Map with bounds
const map2 = new mapboxgl.Map({
container: 'map2',
style: 'mapbox://styles/mapbox/satellite-v9',
bounds: [[-74.04728, 40.68392], [-73.91058, 40.87764]],
fitBoundsOptions: { padding: 50 }
});
// Map with interaction controls
const map3 = new mapboxgl.Map({
container: 'map3',
style: 'mapbox://styles/mapbox/outdoors-v12',
center: [-122.4194, 37.7749],
zoom: 12,
pitch: 45,
bearing: -17.6,
antialias: true,
scrollZoom: { around: 'center' },
dragPan: { linearity: 0.3, easing: 'bezier(0, 0, 0.3, 1)' }
});Add, remove, and manage data sources for map layers.
/**
* Add a data source to the map
* @param id - Unique identifier for the source
* @param source - Source specification object
* @returns Map instance for chaining
*/
addSource(id: string, source: SourceSpecification): Map;
/**
* Get a data source by ID
* @param id - Source identifier
* @returns Source instance or undefined if not found
*/
getSource(id: string): Source | undefined;
/**
* Remove a data source from the map
* @param id - Source identifier
* @returns Map instance for chaining
*/
removeSource(id: string): Map;Usage Examples:
// Add GeoJSON source
map.addSource('earthquake-data', {
type: 'geojson',
data: 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson'
});
// Add vector tile source
map.addSource('mapbox-streets', {
type: 'vector',
url: 'mapbox://mapbox.mapbox-streets-v8'
});
// Add raster source
map.addSource('satellite-imagery', {
type: 'raster',
tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'],
tileSize: 256,
attribution: '© Esri'
});Add, remove, and manage rendering layers that visualize data sources.
/**
* Add a rendering layer to the map
* @param layer - Layer specification object
* @param beforeId - Optional ID of layer to insert before
* @returns Map instance for chaining
*/
addLayer(layer: LayerSpecification, beforeId?: string): Map;
/**
* Get a layer by ID
* @param id - Layer identifier
* @returns Layer instance or undefined if not found
*/
getLayer(id: string): Layer | undefined;
/**
* Remove a layer from the map
* @param id - Layer identifier
* @returns Map instance for chaining
*/
removeLayer(id: string): Map;
/**
* Move a layer to a different position in the layer stack
* @param id - Layer identifier to move
* @param beforeId - Optional ID of layer to move before
* @returns Map instance for chaining
*/
moveLayer(id: string, beforeId?: string): Map;Usage Examples:
// Add fill layer
map.addLayer({
id: 'earthquake-heat',
type: 'fill',
source: 'earthquake-data',
paint: {
'fill-color': [
'interpolate',
['linear'],
['get', 'mag'],
0, '#FCA107',
6, '#7F3121'
],
'fill-opacity': 0.75
}
});
// Add symbol layer with text
map.addLayer({
id: 'earthquake-labels',
type: 'symbol',
source: 'earthquake-data',
layout: {
'text-field': ['get', 'title'],
'text-size': 12,
'text-offset': [0, 1.25],
'text-anchor': 'top'
}
});Query rendered features and source features for interaction and data analysis.
/**
* Query rendered features at a point or within a bounding box
* @param geometry - Point or bounding box to query, or undefined for all features
* @param options - Query options including layers and filters
* @returns Array of GeoJSON features
*/
queryRenderedFeatures(
geometry?: PointLike | [PointLike, PointLike],
options?: QueryRenderedFeaturesParams
): MapboxGeoJSONFeature[];
/**
* Query all features in a source
* @param sourceId - Source identifier to query
* @param options - Query options including source layer and filters
* @returns Array of GeoJSON features
*/
querySourceFeatures(
sourceId: string,
options?: QuerySourceFeaturesParams
): MapboxGeoJSONFeature[];
interface QueryRenderedFeaturesParams {
layers?: string[];
filter?: FilterSpecification;
validate?: boolean;
}
interface QuerySourceFeaturesParams {
sourceLayer?: string;
filter?: FilterSpecification;
validate?: boolean;
}Usage Examples:
// Query features on click
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['earthquake-heat']
});
if (features.length > 0) {
console.log('Clicked earthquake:', features[0].properties);
}
});
// Query all features in a source
const allEarthquakes = map.querySourceFeatures('earthquake-data', {
filter: ['>', ['get', 'mag'], 5.0]
});Convert between geographic and screen coordinates.
/**
* Convert geographic coordinates to screen coordinates
* @param lnglat - Geographic coordinates
* @param altitude - Optional altitude in meters
* @returns Screen coordinates as Point
*/
project(lnglat: LngLatLike, altitude?: number): Point;
/**
* Convert screen coordinates to geographic coordinates
* @param point - Screen coordinates
* @param altitude - Optional altitude in meters
* @returns Geographic coordinates as LngLat
*/
unproject(point: PointLike, altitude?: number): LngLat;Advanced 3D camera positioning and free camera manipulation.
/**
* Returns a FreeCameraOptions object for direct camera manipulation
* @returns FreeCameraOptions object representing current camera state
*/
getFreeCameraOptions(): FreeCameraOptions;
/**
* Sets camera position and orientation using FreeCameraOptions
* @param options - Camera options object
* @param eventData - Additional properties for events
* @returns Map instance for chaining
*/
setFreeCameraOptions(options: FreeCameraOptions, eventData?: any): Map;
/**
* Queries terrain elevation at a specific geographical location
* @param lnglat - The geographical location to query
* @param options - Query options
* @returns The elevation in meters or null if unavailable
*/
queryTerrainElevation(lnglat: LngLatLike, options?: { exaggerated?: boolean }): number | null | undefined;Advanced 3D rendering features including terrain, fog, and atmospheric effects.
/**
* Sets or removes the terrain property of the style
* @param terrain - Terrain specification or null to remove
* @returns Map instance for chaining
*/
setTerrain(terrain?: TerrainSpecification | null): Map;
/**
* Returns the current terrain specification
* @returns Terrain specification or null if not set
*/
getTerrain(): TerrainSpecification | null | undefined;
/**
* Sets or removes the fog property of the style
* @param fog - Fog specification or null to remove
* @returns Map instance for chaining
*/
setFog(fog?: FogSpecification | null): Map;
/**
* Returns the current fog specification
* @returns Fog specification or null if not set
*/
getFog(): FogSpecification | null | undefined;
/**
* Sets lights for the map's style (replaces legacy light API)
* @param lights - Array of lights or null to remove
* @returns Map instance for chaining
*/
setLights(lights?: LightsSpecification[] | null): Map;
/**
* Returns the lights added to the map
* @returns Array of light specifications or null if not set
*/
getLights(): LightsSpecification[] | null | undefined;
/**
* Sets or removes the snow property of the style (experimental)
* @experimental
* @param snow - Snow specification or null to remove
* @returns Map instance for chaining
*/
setSnow(snow?: SnowSpecification | null): Map;
/**
* Returns the current snow specification (experimental)
* @experimental
* @returns Snow specification or null if not set
*/
getSnow(): SnowSpecification | null | undefined;
/**
* Sets or removes the rain property of the style (experimental)
* @experimental
* @param rain - Rain specification or null to remove
* @returns Map instance for chaining
*/
setRain(rain?: RainSpecification | null): Map;
/**
* Returns the current rain specification (experimental)
* @experimental
* @returns Rain specification or null if not set
*/
getRain(): RainSpecification | null | undefined;Dynamic style configuration and import management for flexible styling.
/**
* Sets the imported style configuration value
* @param importId - The name of the imported style
* @param config - The configuration value
* @returns Map instance for chaining
*/
setConfig(importId: string, config: ConfigSpecification): Map;
/**
* Returns the imported style configuration
* @param importId - The name of the imported style
* @returns Configuration specification or null if not found
*/
getConfig(importId: string): ConfigSpecification | null | undefined;
/**
* Adds new import to current style
* @param importSpecification - Specification of import
* @param beforeId - Optional ID of existing import to insert before
* @returns Map instance for chaining
*/
addImport(importSpecification: ImportSpecification, beforeId?: string): Map;
/**
* Removes import from style
* @param importId - Identifier of import to remove
* @returns Map instance for chaining
*/
removeImport(importId: string): Map;
/**
* Sets or removes slot of style layer
* @param layerId - Identifier of style layer
* @param slot - Identifier of slot or null to remove
* @returns Map instance for chaining
*/
setSlot(layerId: string, slot?: string | null): Map;
/**
* Returns current slot of the layer
* @param layerId - Identifier of the layer
* @returns The slot identifier or null
*/
getSlot(layerId: string): string | null | undefined;Methods to query current map state and animation status.
/**
* Returns true if the map is panning, zooming, rotating, or pitching
* @returns True if the map is moving
*/
isMoving(): boolean;
/**
* Returns true if the map is zooming due to camera animation or user gesture
* @returns True if the map is zooming
*/
isZooming(): boolean;
/**
* Returns true if the map is rotating due to camera animation or user gesture
* @returns True if the map is rotating
*/
isRotating(): boolean;// Source specifications
type SourceSpecification =
| GeoJSONSourceSpecification
| VideoSourceSpecification
| ImageSourceSpecification
| CanvasSourceSpecification
| VectorSourceSpecification
| RasterSourceSpecification
| RasterDEMSourceSpecification;
interface GeoJSONSourceSpecification {
type: 'geojson';
data?: GeoJSON.GeoJSON | string;
maxzoom?: number;
attribution?: string;
buffer?: number;
tolerance?: number;
cluster?: boolean;
clusterRadius?: number;
clusterMaxZoom?: number;
clusterProperties?: { [propertyName: string]: [ExpressionSpecification, ExpressionSpecification] };
lineMetrics?: boolean;
generateId?: boolean;
}
// Layer specifications
type LayerSpecification =
| FillLayerSpecification
| LineLayerSpecification
| SymbolLayerSpecification
| CircleLayerSpecification
| HeatmapLayerSpecification
| FillExtrusionLayerSpecification
| RasterLayerSpecification
| HillshadeLayerSpecification
| BackgroundLayerSpecification
| SkyLayerSpecification
| CustomLayerInterface;
interface FillLayerSpecification {
id: string;
type: 'fill';
source: string;
'source-layer'?: string;
minzoom?: number;
maxzoom?: number;
filter?: FilterSpecification;
layout?: FillLayoutSpecification;
paint?: FillPaintSpecification;
}
// Feature selector for feature state operations
interface FeatureSelector {
source: string;
sourceLayer?: string;
id?: string | number;
}
// Feature state object
type FeatureState = { [key: string]: any };
// GeoJSON feature with additional Mapbox properties
interface MapboxGeoJSONFeature extends GeoJSON.Feature {
layer: LayerSpecification;
source: string;
sourceLayer?: string;
state: FeatureState;
}