Skip to content

Map

The Map object represents the map on your page. It exposes methods and properties that enable you to programmatically change the map, and fires events as users interact with it.

You create a Map by specifying a container and other options. Then vietmap GL JS initializes the map on the page and returns your Map object.

new Map class(options: Object)

Parameter

Name Description
options.container(HTMLElement | string) The HTML element in which vietmap GL JS will render the map, or the element's string id . The specified element must have no children.
options.minZoomnumberdefault: 0 The minimum zoom level of the map (0-24).
options.maxZoomnumberdefault: 22 The maximum zoom level of the map (0-24).
options.minPitchnumberdefault: 0 The minimum pitch of the map (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the vietmap project.options.style(Object | string)?The map's vietmap style. This must be an a JSON object conforming to t
options.hash(boolean |string)default: false If true , the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL. For example, http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60 . An additional string may optionally be provided to indicate a parameter-styled hash, e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar , where foo is a custom parameter and bar is an arbitrary hash distinct from the map hash.
options.interactivebooleandefault: true If false , no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.
options.bearingSnapnumberdefault: 7 The threshold, measured in degrees, that determines when the map's bearing will snap to north. For example, with a bearingSnap of 7, if the user rotates the map within 7 degrees of north, the map will automatically snap to exact north.
options.pitchWithRotatebooleandefault: true If false , the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
options.clickTolerancenumberdefault: 3 The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).
options.attributionControlbooleandefault: true If true , an AttributionControl will be added to the map.
options.customAttribution(string | Array)? String or strings to show in an AttributionControl . Only applicable if options.attributionControl is true .
options.vietmapLogobooleandefault: false If true , the vietmap logo will be shown.
options.logoPositionstringdefault: 'bottom-left' A string representing the position of the vietmap wordmark on the map. Valid options are top-left , top-right , bottom-left , bottom-right .
options.failIfMajorPerformanceCaveatbooleandefault: false If true , map creation will fail if the performance of vietmap GL JS would be dramatically worse than expected (i.e. a software renderer would be used).
options.preserveDrawingBufferbooleandefault: false If true , the map's canvas can be exported to a PNG using map.getCanvas().toDataURL() . This is false by default as a performance optimization.
options.antialiasboolean? If true , the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is false by default as a performance optimization.
options.refreshExpiredTilesbooleandefault: true If false , the map won't attempt to re-request tiles once they expire per their HTTP cacheControl / expires headers.
options.maxBoundsLngLatBoundsLike? If set, the map will be constrained to the given bounds.
options.scrollZoom(boolean | Object)default: true If true , the "scroll to zoom" interaction is enabled. An Object value is passed as options to ScrollZoomHandler#enable .
options.boxZoombooleandefault: true If true , the "box zoom" interaction is enabled (see BoxZoomHandler ).
options.dragRotatebooleandefault: true If true , the "drag to rotate" interaction is enabled (see DragRotateHandler ).
options.dragPan(boolean | Object)default: true If true , the "drag to pan" interaction is enabled. An Object value is passed as options to DragPanHandler#enable .
options.keyboardbooleandefault: true If true , keyboard shortcuts are enabled (see KeyboardHandler ).
options.doubleClickZoombooleandefault: true If true , the "double click to zoom" interaction is enabled (see DoubleClickZoomHandler ).
options.touchZoomRotate(boolean | Object)default: true If true , the "pinch to rotate and zoom" interaction is enabled. An Object value is passed as options to TouchZoomRotateHandler#enable .
options.touchPitch(boolean | Object)default: true If true , the "drag to pitch" interaction is enabled. An Object value is passed as options to TouchPitchHandler#enable .
options.trackResizebooleandefault: true If true , the map will automatically resize when the browser window resizes.
options.centerLngLatLikedefault: [0,0] The initial geographical centerpoint of the map. If center is not specified in the constructor options, vietmap GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to [0, 0] Note: vietmap GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.
options.zoomnumberdefault: 0 The initial zoom level of the map. If zoom is not specified in the constructor options, vietmap GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to 0 .
options.bearingnumberdefault: 0 The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If bearing is not specified in the constructor options, vietmap GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to 0 .
options.pitchnumberdefault: 0 The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-85). If pitch is not specified in the constructor options, vietmap GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to 0 . Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the vietmap project.
options.boundsLngLatBoundsLike? The initial bounds of the map. If bounds is specified, it overrides center and zoom constructor options.
options.fitBoundsOptionsObject? A Map#fitBounds options object to use only when fitting the initial bounds provided above
options.renderWorldCopiesbooleandefault: true If true , multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false :When the map is zoomed out far enough that a single representation of the world does not fill the map's entirecontainer, there will be blank space beyond 180 and -180 degrees longitude.Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of themap and the other on the left edge of the map) at every zoom level.
options.maxTileCacheSizenumberdefault: null The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport.
options.localIdeographFontFamilystringdefault: 'sans-serif' Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set to false , to enable font settings from the map's style for these glyph ranges. The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See Use locally generated ideographs .)
options.transformRequestRequestTransformFunctiondefault: null A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with a url property and optionally headers and credentials properties.
options.collectResourceTimingbooleandefault: false If true , Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a resourceTiming property of relevant data events.
options.fadeDurationnumberdefault: 300 Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.
options.crossSourceCollisionsbooleandefault: true If true , symbols from multiple sources can collide with each other during collision detection. If false , collision detection is run separately for the symbols in each source.
options.localeObjectdefault: null A patch to apply to the default localization table for UI strings, e.g. control tooltips. The locale object maps namespaced UI string IDs to translated strings in the target language; see src/ui/default_locale.js for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).
options.pixelRationumber? The pixel ratio. The canvas' width attribute will be container.clientWidth * pixelRatio and its height attribute will be container.clientHeight * pixelRatio . Defaults to devicePixelRatio if not specified.example

Example


var map = new vietmapgl.Map({
    container: 'map',
    center: [-122.420679, 37.772537],
    zoom: 13,
    style: style_object,
    hash: true,
    transformRequest: (url, resourceType)=> {
    if(resourceType === 'Source' && url.startsWith('http://myHost')) {
        return {
            url: url.replace('http', 'https'),
            headers: { 'my-custom-header': true},
            credentials: 'include'  // Include cookies for cross-origin requests
        }
    }
    }
});

Instance Members

addControl(control, position?)

Adds an IControl to the map, calling control.onAdd(this).

Parameters

control(IControl)The IControl to add. position(string?)position on the map to which the control will be added. Valid values are 'top-left' , 'top-right' , 'bottom-left' , and 'bottom-right' . Defaults to 'top-right' .

Returns

Map: this

Example

// Add zoom and rotation controls to the map.
map.addControl(new vietmapgl.NavigationControl());

Related

Display map navigation controls

addImage(id, image, options)

Add an image to the style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with icon-image, background-pattern, fill-pattern, or line-pattern. A Map.event:error event will be fired if there is not enough space in the sprite to add this image.

Parameters

  • id(string)

  • The ID of the image.

  • image((HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface))The image as an HTMLImageElement , ImageData , ImageBitmap or object with width , height , and data properties with the same format as ImageData .

  • options(Partial)(default {}) Options object.

Name Description
options.pixelRatioanydefault: 1 The ratio of pixels in the image to physical pixels on the screen
options.sdfanydefault: false Whether the image should be interpreted as an SDF image
options.stretchXany [[x1, x2], ...] If icon-text-fit is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.
options.stretchYany [[y1, y2], ...] If icon-text-fit is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.
options.contentany [x1, y1, x2, y2] If icon-text-fit is used in a layer with this image, this option defines the part of the image that can be covered by the content in text-field .example

Example

// If the style's sprite does not already contain an image with ID 'cat',
// add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) {
    if (error) throw error;
    if (!map.hasImage('cat')) map.addImage('cat', image);
});


// Add a stretchable image that can be used with `icon-text-fit`
// In this example, the image is 600px wide by 400px high.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) {
    if (error) throw error;
    if (!map.hasImage('border-image')) {
        map.addImage('border-image', image, {
            content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
            stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
            stretchY: [[16, 384]], // stretch everything vertically except the 16px border
        });
    }
});

Related

  • Use HTMLImageElement : Add an icon to the map

  • Use ImageData : Add a generated icon to the map

addLayer(layer, beforeId)

Adds a vietmap style layer to the map's style.

A layer defines how data from a specified source will be styled. Read more about layer types and available paint and layout properties in the vietmap Style Specification.

Parameters

layer((Object | CustomLayerInterface))The layer to add, conforming to either the vietmap Style Specification's layer definition or, less commonly, the CustomLayerInterface specification. The vietmap Style Specification's layer definition is appropriate for most layers.

Name Description
layer.idstring A unique identifer that you define.
layer.typestring The type of layer (for example fill or symbol ). A list of layer types is available in the vietmap Style Specification .(This can also be custom. For more information, see CustomLayerInterface.)
layer.source(string | Object)? The data source for the layer. Reference a source that has already been defined using the source's unique id. Reference a new source using a source object (as defined in the vietmap Style Specification ) directly. This is required for all layer.type options except for custom .
layer.sourceLayerstring? (optional) The name of the source layer within the specified layer.source to use for this style layer. This is only applicable for vector tile sources and is required when layer.source is of the type vector .
layer.filterarray? (optional) An expression specifying conditions on source features. Only features that match the filter are displayed. The vietmap Style Specification includes more information on the limitations of the filter parameter and a complete list of available expressions . If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed.
layer.paintObject? (optional) Paint properties for the layer. Available paint properties vary by layer.type . A full list of paint properties for each layer type is available in the vietmap Style Specification . If no paint properties are specified, default values will be used.
layer.layoutObject? (optional) Layout properties for the layer. Available layout properties vary by layer.type . A full list of layout properties for each layer type is available in the vietmap Style Specification . If no layout properties are specified, default values will be used.
layer.maxzoomnumber? (optional) The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden. The value can be any number between 0 and 24 (inclusive). If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.
layer.minzoomnumber? (optional) The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden. The value can be any number between 0 and 24 (inclusive). If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.
layer.metadataObject? (optional) Arbitrary properties useful to track with the layer, but do not influence rendering.
layer.renderingModestring? This is only applicable for layers with the type custom . See CustomLayerInterface for more information.

Returns

Map: this

Example

// Add a circle layer with a vector source
map.addLayer({
    id: 'points-of-interest',
    source: {
        type: 'vector',
        url: 'https://demotiles.vietmap.org/tiles/tiles.json'
    },
    'source-layer': 'poi_label',
    type: 'circle',
    paint: {
    // vietmap Style Specification paint properties
    },
    layout: {
    // vietmap Style Specification layout properties
    }
});


// Define a source before using it to create a new layer
map.addSource('state-data', {
    type: 'geojson',
    data: 'path/to/data.geojson'
});

map.addLayer({
    id: 'states',
    // References the GeoJSON source defined above
    // and does not require a `source-layer`
    source: 'state-data',
    type: 'symbol',
    layout: {
    // Set the label content to the
    // feature's `name` property
    text-field: ['get', 'name']
    }
});


// Add a new symbol layer before an existing layer
map.addLayer({
    id: 'states',
    // References a source that's already been defined
    source: 'state-data',
    type: 'symbol',
    layout: {
        // Set the label content to the
        // feature's `name` property
        text-field: ['get', 'name']
    }
    // Add the layer before the existing `cities` layer
}, 'cities');

Related

  • Create and style clusters

  • Add a vector tile source

  • Add a WMS source

addSource(id, source)

Adds a source to the map's style.

Parameters

  • id(string)The ID of the source to add. Must not conflict with existing sources.

  • source(Object)The source object, conforming to the vietmap Style Specification's source definition or CanvasSourceOptions .

Return

Map: this

Example

map.addSource('my-data', {
    type: 'vector',
    url: 'https://demotiles.vietmap.org/tiles/tiles.json'
});


map.addSource('my-data', {
    "type": "geojson",
    "data": {
        "type": "Feature",
        "geometry": {
        "type": "Point",
        "coordinates": [-77.0323, 38.9131]
    },
    "properties": {
        "title": "Mapbox DC",
        "marker-symbol": "monument"
    }
    }
});

Related

  • GeoJSON source: Add live realtime data

addTilesLoaded()

Returns a Boolean indicating whether all tiles in the viewport from all sources on the style are loaded.

Returns(http://192.168.10.112:8099/sdk/docs/api/map/#aretilesloaded-returns)

boolean: A Boolean indicating whether all tiles are loaded.

Example

var tilesLoaded = map.areTilesLoaded();

boxZoom

The map's BoxZoomHandler, which implements zooming using a drag gesture with the Shift key pressed. Find more details and examples using boxZoom in the BoxZoomHandler section.

cameraForBounds(bound, options?)

Parameters

bounds(LngLatBoundsLike)Calculate the center for these bounds in the viewport and use the highest zoom level up to and including Map#getMaxZoom() that fits in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.

options(CameraForBoundsOptions?)Options object

Name Description
options.padding(number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.bearingnumberdefault: 0 Desired map bearing at end of animation, in degrees.
options.offsetPointLikedefault: [0,0] The center of the given bounds relative to the map's center, measured in pixels.
options.maxZoomnumber? The maximum zoom level to allow when the camera would transition to the specified bounds.

Returns

CenterZoomBearing: If map is able to fit to provided bounds, returns center , zoom , and bearing . If map is unable to fit, method will warn and return undefined.

Example

var bbox = [[-79, 43], [-73, 45]];
var newCameraTransform = map.cameraForBounds(bbox, {
    padding: {top: 10, bottom:25, left: 15, right: 5}
});

doupleClickZoom

The map's DoubleClickZoomHandler, which allows the user to zoom by double clicking. Find more details and examples using doubleClickZoom in the DoubleClickZoomHandler section.

dragPan

The map's DragPanHandler, which implements dragging the map with a mouse or touch gesture. Find more details and examples using dragPan in the DragPanHandler section.

dragRotate

The map's DragRotateHandler, which implements rotating the map while dragging with the right mouse button or with the Control key pressed. Find more details and examples using dragRotate in the DragRotateHandler section.

easeTo(options, eventData?)

Changes any combination of center, zoom, bearing, pitch, and padding with an animated transition between old and new values. The map will retain its current values for any details not specified in options.

Note: The transition will happen instantly if the user has enabled the reduced motion accesibility feature enabled in their operating system, unless options includes essential: true.

Parameters

  • options(any)Options describing the destination and animation of the transition. Accepts CameraOptions and AnimationOptions .

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Related

Navigate the map with game-like controls

fitBounds(bounds, options?, eventData?)

Pans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map's bearing to 0 if bearing is nonzero.

Parameters

bounds(LngLatBoundsLike) Center these bounds in the viewport and use the highest zoom level up to and including Map#getMaxZoom() that fits them in the viewport.

options(FitBoundsOptions? ) Options supports all properties from AnimationOptions and CameraOptions in addition to the fields below.

Name Description
options.padding(number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.linearbooleandefault: false If true , the map transitions using Map#easeTo . If false , the map transitions using Map#flyTo . See those functions and AnimationOptions for information about options available.
options.easingFunction? An easing function for the animated transition. See AnimationOptions .
options.offsetPointLikedefault: [0,0] The center of the given bounds relative to the map's center, measured in pixels.
options.maxZoomnumber? number?The maximum zoom level to allow when the map view transitions to the specified bounds.

Returns

Map: this

Example

var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
    padding: {top: 10, bottom:25, left: 15, right: 5}
});

fitScreenCoordinates(p0, p1, bearing, options?, eventData?)

Pans, rotates and zooms the map to to fit the box made by points p0 and p1 once the map is rotated to the specified bearing. To zoom without rotating, pass in the current map bearing.

Parameters

p0(PointLike) First point on screen, in pixel coordinates

p1(PointLike) Second point on screen, in pixel coordinates

bearing(number) Desired map bearing at end of animation, in degrees

options(FitBoundsOptions?) Options object

Name Description
options.padding(number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.linearbooleandefault: false If true , the map transitions using Map#easeTo . If false , the map transitions using Map#flyTo . See those functions and AnimationOptions for information about options available.
options.easingFunction? An easing function for the animated transition. See AnimationOptions .
options.offsetPointLikedefault: [0,0] The center of the given bounds relative to the map's center, measured in pixels.
options.maxZoomnumber? The maximum zoom level to allow when the map view transitions to the specified bounds.

Returns

Map: this

Example

var p0 = [220, 400];
var p1 = [500, 900];
map.fitScreenCoordinates(p0, p1, map.getBearing(), {
    padding: {top: 10, bottom:25, left: 15, right: 5}
});

flyTo(options, eventData?)

Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance.

Note: The animation will be skipped, and this will behave equivalently to jumpTo if the user has the reduced motion accesibility feature enabled in their operating system, unless 'options' includes essential: true.

Parameters

options(FlyToOptions) Options describing the destination and animation of the transition. Accepts CameraOptions , AnimationOptions , and the following additional options.

Name Description
options.curvenumberdefault: 1.42 The zooming "curve" that will occur along the flight path. A high value maximizes zooming for an exaggerated animation, while a low value minimizes zooming for an effect closer to Map#easeTo . 1.42 is the average value selected by participants in the user study discussed in van Wijk (2003) . A value of Math.pow(6, 0.25) would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion.
options.minZoomnumber? The zero-based zoom level at the peak of the flight path. If options.curve is specified, this option is ignored.
options.speednumberdefault: 1.2 The average speed of the animation defined in relation to options.curve . A speed of 1.2 means that the map appears to move along the flight path by 1.2 times options.curve screenfuls every second. A screenful is the map's visible span. It does not correspond to a fixed physical distance, but varies by zoom level.
options.screenSpeednumber? The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. If options.speed is specified, this option is ignored.
options.maxDurationnumber? The animation's maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0.

eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// fly with default options to null island
map.flyTo({center: [0, 0], zoom: 9});
// using flyTo options
map.flyTo({
    center: [0, 0],
    zoom: 9,
    speed: 0.2,
    curve: 1,
    easing(t) {
    return t;
    }
});

Related

  • Fly to a location
  • Slowly fly to a location
  • Fly to a location based on scroll position

getBearing()

Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Returns

number: The map's current bearing.

Related

Navigate the map with game-like controls

getBounds()

Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.

Returns

LngLatBounds: The geographical bounds of the map as LngLatBounds .

Example

var bounds = map.getBounds();

getCanvas()

Returns the map's canvas element.

Return

HTMLCanvasElement: The map's canvas element.

Related

  • Measure distances
  • Display a popup on hover
  • Center the map on a clicked symbol

getCanvasContainer()

Returns the HTML element containing the map's canvas element.

If you want to add non-GL overlays to the map, you should append them to this element.

This is the element to which event bindings for map interactivity (such as panning and zooming) are attached. It will receive bubbled events from child elements such as the canvas, but not from map controls.

Returns

HTMLElement: The container of the map's canvas .

Related

Create a draggable point

getCenter()

Returns the map's geographical centerpoint.

Returns

LngLat: The map's geographical centerpoint.

Example

// return a LngLat object such as {lng: 0, lat: 0}
var center = map.getCenter();
// access longitude and latitude values directly
var {lng, lat} = map.getCenter();

getContainer()

Returns the map's containing HTML element.

Returns

HTMLElement: The map's container.

getFeatureState()

Gets the state of a feature. A feature's state is a set of user-defined key-value pairs that are assigned to a feature at runtime. Features are identified by their feature.id attribute, which can be any number or string.

Note: To access the values in a feature's state object for the purposes of styling the feature, use the feature-state expression.

Parameters

feature(Object)Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.

Name Description
feature.id(string | number) Unique id of the feature.
feature.sourcestring The id of the vector or GeoJSON source for the feature.
feature.sourceLayerstring? (optional) For vector tile sources, sourceLayer is required.

Returns

Object: The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.

Example

// When the mouse moves over the `my-layer` layer,
// get the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', function(e) {
    if (e.features.length > 0) {
        map.getFeatureState({
            source: 'my-source',
            sourceLayer: 'my-source-layer',
            id: e.features[0].id
        });
    }
});

getFilter(layerId)

Returns the filter applied to the specified style layer.

Parameters

layerId(string)The ID of the style layer whose filter to get.

Returns

Array: The layer's filter.

getLayer(id)

Returns the layer with the specified ID in the map's style.

Parameters

id(string)The ID of the layer to get.

Returns

StyleLayer: The layer with the specified ID, or undefined if the ID corresponds to no existing layers.

Example

var stateDataLayer = map.getLayer('state-data');

Related

  • Filter symbols by toggling a list

  • Filter symbols by text input

getLayoutProperty(layerId,name)

Returns the value of a layout property in the specified style layer.

Parameters

  • layerId(string)The ID of the layer to get the layout property from.
  • name(string)The name of the layout property to get.

Returns

any: The value of the specified layout property.

getLight()

Returns the value of the light object.

Returns

Object: light Light properties of the style.

getMaxBounds()

Returns the maximum geographical bounds the map is constrained to, or null if none set.

Returns

(LngLatBounds | null): The map object.

Example

var maxBounds = map.getMaxBounds();

getMaxPitch()

Returns the map's maximum allowable pitch.

Returns

number: maxPitch

getMaxZoom()

Returns the map's maximum allowable zoom level.

Returns

number: maxZoom

Example

var maxZoom = map.getMaxZoom();

getMinPitch()

Returns the map's minimum allowable pitch.

Returns

number: minPitch

getMinZoom()

Returns the map's minimum allowable zoom level.

Returns

number: minZoom

Example

var minZoom = map.getMinZoom();

getPadding()

Returns the current padding applied around the map viewport.

Returns

PaddingOptions: The current padding around the map viewport.

getPaintProperty(layerId, name)

Returns the value of a paint property in the specified style layer.

Parameters

layerId(string)The ID of the layer to get the paint property from.

name(string)The name of a paint property to get.

Returns

any: The value of the specified paint property.

getPitch

Returns the map's current pitch (tilt).

Returns

number: The map's current pitch, measured in degrees away from the plane of the screen.

getPixelRatio()

Returns the map's pixel ratio.

Returns

number: The pixel ratio.

getRenderWorldCopies()

Returns the state of renderWorldCopies. If true, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false:

When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude.

Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.

Returns

boolean: renderWorldCopies

Example

var worldCopiesRendered = map.getRenderWorldCopies();

Related

Render world copies

getSource(id)

Returns the source with the specified ID in the map's style.

This method is often used to update a source using the instance members for the relevant source type as defined in Sources. For Example, setting the data for a GeoJSON source or updating the url and coordinates of an image source.

Parameters

id(string)The ID of the source to get.

Returns

(Source | undefined): The style source with the specified ID or undefined if the ID corresponds to no existing sources. The shape of the object varies by source type. A list of options for each source type is available on the vietmap Style Specification's Sources page.

Example

var sourceObject = map.getSource('points');

Related

  • Create a draggable point

  • Animate a point

  • Add live realtime data

getStyle()

Returns the map's vietmap style object, a JSON object which can be used to recreate the map's style.

Returns

Object: The map's style JSON object.

Example

var styleJson = map.getStyle();

getZoom()

Returns the map's current zoom level.

Returns

number: The map's current zoom level.

Example

map.getZoom();

hasControl(control)

Checks if a control exists on the map.

Parameters

control(IControl)The IControl to check.

Returns

boolean: True if map contains control.

Example

// Define a new navigation control.
var navigation = new vietmapgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Check that the navigation control exists on the map.
map.hasControl(navigation);

hasImage(id)

Check whether or not an image with a specific ID exists in the style. This checks both images in the style's original sprite and any images that have been added at runtime using Map#addImage.

Parameters

id(string)The ID of the image.

Returns

boolean: A Boolean indicating whether the image exists.

Example

// Check if an image with the ID 'cat' exists in
// the style's sprite.
var catIconExists = map.hasImage('cat');

isMoving()

Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.

Returns

boolean: True if the map is moving.

Example

var isMoving = map.isMoving();

isRotating()

Returns true if the map is rotating due to a camera animation or user gesture.

Returns

boolean: True if the map is rotating.

Example

map.isRotating();

isSourceLoaded(id)

Returns a Boolean indicating whether the source is loaded. Returns true if the source with the given ID in the map's style has no outstanding network requests, otherwise false.

Parameters

id(string)The ID of the source to be checked.

Returns

boolean: A Boolean indicating whether the source is loaded.

Example

var sourceLoaded = map.isSourceLoaded('bathymetry-data');

isStyleLoaded()

Returns a Boolean indicating whether the map's style is fully loaded.

Returns

boolean: A Boolean indicating whether the style is fully loaded.

Example

var styleLoadStatus = map.isStyleLoaded();

isZooming()

Returns true if the map is zooming due to a camera animation or user gesture.

Returns

boolean: True if the map is zooming.

Example

var isZooming = map.isZooming();

jumpTo(options, eventData?)

Changes any combination of center, zoom, bearing, and pitch, without an animated transition. The map will retain its current values for any details not specified in options.

Parameters

  • options(JumpToOptions)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// jump to coordinates at current zoom
map.jumpTo({center: [0, 0]});
// jump with zoom, pitch, and bearing options
map.jumpTo({
center: [0, 0],
zoom: 8,
pitch: 45,
bearing: 90
});

Related

  • Jump to a series of locations

  • Update a feature in realtime

keyboard

The map's KeyboardHandler, which allows the user to zoom, rotate, and pan the map using keyboard shortcuts. Find more details and examples using keyboard in the KeyboardHandler section.

listImages()

Returns an Array of strings containing the IDs of all images currently available in the map. This includes both images from the style's original sprite and any images that have been added at runtime using Map#addImage.

Returns

Array: An Array of strings containing the names of all sprites/images currently available in the map.

Example

var allImages = map.listImages();

loaded()

Returns a Boolean indicating whether the map is fully loaded.

Returns false if the style is not yet fully loaded, or if there has been a change to the sources or style that has not yet fully loaded.

Returns

boolean: A Boolean indicating whether the map is fully loaded.

loadImage(url, callback)

Load an image from an external URL to be used with Map#addImage. External domains must support CORS.

Parameters

url(string)The URL of the image file. Image file must be in png, webp, or jpg format.

callback(Callback<(HTMLImageElement | ImageBitmap)>)Expecting callback(error, data) . Called when the image has loaded or with an error argument if there is an error.

Example

// Load an image from an external URL.
map.loadImage('http://placekitten.com/50/50', function(error, image) {
if (error) throw error;
// Add the loaded image to the style's sprite with the ID 'kitten'.
map.addImage('kitten', image);
});

Related

  • Add an icon to the map

  • moveLayer(id, beforeId?)

  • Moves a layer to a different z-position.

Parameters

  • id(string)The ID of the layer to move.
  • beforeId(string?)The ID of an existing layer to insert the new layer before. When viewing the map, the id layer will appear beneath the beforeId layer. If beforeId is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.

Returns

Map: this

Example

// Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.
map.moveLayer('polygon', 'country-label');

off(type, listener)

Removes an event listener previously added with Map#on.

Parameters

type(string)The event type previously used to install the listener.

listener(Function)The function previously installed as a listener.

Returns

Map: this

off(type, layer, listener, layerIdOrListener)

Removes an event listener for layer-specific events previously added with Map#on.

Parameters

  • type(string)The event type previously used to install the listener.

  • layer(string)

  • listener(Function)The function previously installed as a listener.

  • layerIdOrListener(string)The layer ID or listener previously used to install the listener.

Returns

Map: this

on(type, layer, listener, layerIdOrListener)

Adds a listener for events of a specified type, optionally limited to features in a specified style layer.

Parameters

type(string)The event type to listen for. Events compatible with the optional layerId parameter are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.

Event Compatible with layerId
mousedown yes
mouseup yes
mouseover yes
mouseout yes
mousemove yes
mouseenter yes(required)
mouseleave yes(required)
click yes
dbclick yes
contextmenu yes
touchstart yes
touchend yes
touchcancel yes
wheel
resize
remove
touchmove
movestart
move
moveend
dragstart
drag
dragend
zoomstart
zoom
zoomend
rotatestart
rotate
rotateend
pitchstart
pitch
pitchend
boxzoomstart
boxzoomend
boxzoomcancel
webglcontextlost
webglcontextrestored
load
render
idle
error
data
styledata
sourcedata
dataloading
styledataloading
sourcedataloading
styleimagemissing
dataabort
sourcedataabort
  • layer(string)

  • listener(Function)The function to be called when the event is fired.

  • layerIdOrListener((string | Listener))The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location is within a visible feature in this layer. The event will have a features property containing an array of the matching features. If layerIdOrListener is not supplied, the event will not have a features property. Please note that many event types are not compatible with the optional layerIdOrListener parameter.

Returns

Map: this

Example

// Set an event listener that will fire
// when the map has finished loading
map.on('load', function() {
// Once the map has finished loading,
// add a new layer
map.addLayer({
id: 'points-of-interest',
source: {
type: 'vector',
url: 'http://192.168.10.107:8080/sdk/docs/style-spec/'
},
'source-layer': 'poi_label',
type: 'circle',
paint: {
// vietmap Style Specification paint properties
},
layout: {
// vietmap Style Specification layout properties
}
});
});


// Set an event listener that will fire
// when a feature on the countries layer of the map is clicked
map.on('click', 'countries', function(e) {
new vietmapgl.Popup()
.setLngLat(e.lngLat)
.setHTML(`Country name: ${e.features[0].properties.name}`)
.addTo(map);
});

Related

  • Display popup on click

  • Center the map on a clicked symbol

  • Create a hover effect

  • Create a draggable marker

once(type, listener)

Adds a listener that will be called only once to a specified event type.

Parameters

  • type(string)The event type to add a listener for.

  • listener(Function)The function to be called when the event is fired. The listener function is called with the data object passed to fire , extended with target and type properties.

Returns

Map: this

once(type, layer, listener, layerIdOrListener)

Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer.

Parameters

  • type(string)The event type to listen for; one of 'mousedown' , 'mouseup' , 'click' , 'dblclick' , 'mousemove' , 'mouseenter' , 'mouseleave' , 'mouseover' , 'mouseout' , 'contextmenu' , 'touchstart' , 'touchend' , or 'touchcancel' . mouseenter and mouseover events are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. mouseleave and mouseout events are triggered when the cursor leaves a visible portion of the specified layer, or leaves the map canvas.

  • layer(string)

  • listener(Function)The function to be called when the event is fired.

  • layerIdOrListener(string)The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible feature in this layer will trigger the listener. The event will have a features property containing an array of the matching features.

Returns

Map: this

panBy(offset, options?, eventData?)

Pans the map by the specified offset.

Parameters

  • offset(PointLike)x and y coordinates by which to pan the map.

  • options(AnimationOptions?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Related

  • Navigate the map with game-like controls

  • panTo(lnglat, options?, eventData?)

  • Pans the map to the specified location with an animated transition.

Parameters

  • lnglat(LngLatLike)The location to pan the map to.

  • options(AnimationOptions?)Options describing the destination and animation of the transition.

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

map.panTo([-74, 38]);


// Specify that the panTo animation should last 5000 milliseconds.
map.panTo([-74, 38], {duration: 5000});

Related

Update a feature in realtime

project(lnglat)

Returns a Point representing pixel coordinates, relative to the map's container, that correspond to the specified geographical location.

Parameters

lnglat(LngLatLike)The geographical location to project.

Returns

Point: The Point corresponding to lnglat , relative to the map's container .

Example

var coordinate = [-122.420679, 37.772537];
var point = map.project(coordinate);

queryRenderedFeatures(geometry?, option?)

Returns an array of MapGeoJSONFeature objects representing visible features that satisfy the query parameters.

Parameters

geometry((PointLike | Array)?) The geometry of the query region: either a single point or southwest and northeast points describing a bounding box. Omitting this parameter (i.e. calling Map#queryRenderedFeatures with zero arguments, or with only a options argument) is equivalent to passing a bounding box encompassing the entire map viewport.

options(Object?)Options object.

Name Description
options.layersArray? An array of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.
options.filterArray? TA filter to limit query results.
options.validatebooleandefault: true Whether to check if the [options.filter] conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Array: An array of MapGeoJSONFeature objects. The properties value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e. null, Array, and Object values are not supported).

Each feature includes top-level layer, source, and sourceLayer properties. The layer property is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature.

Only features that are currently rendered are included. Some features will not be included, like:

Features from layers whose visibility property is "none". Features from layers whose zoom range excludes the current zoom level. Symbol features that have been hidden due to text or icon collision. Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0.

The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low zoom levels) are returned only once (though subject to the following caveat).

Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.

Example

// Find all features at a point
var features = map.queryRenderedFeatures(
[20, 35],
{ layers: ['my-layer-name'] }
);


// Find all features within a static bounding box
var features = map.queryRenderedFeatures(
[[10, 20], [30, 50]],
{ layers: ['my-layer-name'] }
);


// Find all features within a bounding box around a point
var width = 10;
var height = 20;
var features = map.queryRenderedFeatures([
[point.x - width / 2, point.y - height / 2],
[point.x + width / 2, point.y + height / 2]
], { layers: ['my-layer-name'] });


// Query all rendered features from a single layer
var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });

Related

Get features under the mouse pointer

querySourceFeatures(sourceId, parameters?)

Returns an array of MapGeoJSONFeature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.

Parameters

  • sourceId(string)The ID of the vector tile or GeoJSON source to query.

  • parameters(Object?)Options object.

Name Description
parameters.sourceLayerstring? The name of the source layer to query. For vector tile sources, this parameter is required. For GeoJSON sources, it is ignored.
parameters.filterArray? A filter to limit query results.
parameters.validatebooleandefault: true Whether to check if the [parameters.filter] conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Array: An array of MapGeoJSONFeature objects. The properties value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e. null, Array, and Object values are not supported).

Each feature includes top-level layer, source, and sourceLayer properties. The layer property is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature.

Only features that are currently rendered are included. Some features will not be included, like:

Features from layers whose visibility property is "none". Features from layers whose zoom range excludes the current zoom level. Symbol features that have been hidden due to text or icon collision. Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0.

The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low zoom levels) are returned only once (though subject to the following caveat).

Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.

Example

// Find all features in one source layer in a vector source
var features = map.querySourceFeatures('your-source-id', {
sourceLayer: 'your-source-layer'
});

redraw()

Force a synchronous redraw of the map.

Returns

Map: this

Example

map.redraw();

remove()

Clean up and release all internal resources associated with this map.

This includes DOM elements, event bindings, web workers, and WebGL resources.

Use this method when you are done using the map and wish to ensure that it no longer consumes browser resources. Afterwards, you must not call any other methods on the map.

removeControl(control)

Removes the control from the map.

Parameters

control(IControl)The IControl to remove.

Returns

Map: this

Example

// Define a new navigation control.
var navigation = new vietmapgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Remove zoom and rotation controls from the map.
map.removeControl(navigation);

removeFeaturesState(target, key)

Removes the state of a feature, setting it back to the default behavior. If only a target.source is specified, it will remove the state for all features from that source. If target.id is also specified, it will remove all keys for that feature's state. If key is also specified, it removes only that key from that feature's state. Features are identified by their feature.id attribute, which can be any number or string.

Parameters

target(Object)Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.

Name Description
target.id(string number)
target.sourcestring The id of the vector or GeoJSON source for the feature.
target.sourceLayerstring? (optional) For vector tile sources, sourceLayer is required.

key(string)(optional) The key in the feature state to reset.

Example

// Reset the entire state object for all features
// in the `my-source` source
map.removeFeatureState({
source: 'my-source'
});


// When the mouse leaves the `my-layer` layer,
// reset the entire state object for the
// feature under the mouse
map.on('mouseleave', 'my-layer', function(e) {
map.removeFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id
});
});


// When the mouse leaves the `my-layer` layer,
// reset only the `hover` key-value pair in the
// state for the feature under the mouse
map.on('mouseleave', 'my-layer', function(e) {
map.removeFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id
}, 'hover');
});

removeImage(id)

Remove an image from a style. This can be an image from the style's original sprite or any images that have been added at runtime using Map#addImage.

Parameters

id(string)The ID of the image.

Example

// If an image with the ID 'cat' exists in
// the style's sprite, remove it.
if (map.hasImage('cat')) map.removeImage('cat');

removeLayer(id)

Removes the layer with the given ID from the map's style.

If no such layer exists, an error event is fired.

Parameters

id(string)id of the layer to remove

Example

// If a layer with ID 'state-data' exists, remove it.
if (map.getLayer('state-data')) map.removeLayer('state-data');

removeSource(id)

Removes a source from the map's style.

Parameters

id(string)The ID of the source to remove.

Returns

Map: this

Example

map.removeSource('bathymetry-data');

repaint

Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance.

resetNorth(option?, eventData?)

Rotates the map so that north is up (0° bearing), with an animated transition.

Parameters

  • options(AnimationOptions?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

resetNorthPitch(option?, eventData?)

Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.

Parameters

options(AnimationOptions?)Options object

eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

resize(eventData?)

Resizes the map according to the dimensions of its container element.

Checks if the map container size changed and updates the map if it has changed. This method must be called after the map's container is resized programmatically or when the map is shown after being initially hidden with CSS.

Parameters

eventData(any?)Additional properties to be passed to movestart , move , resize , and moveend events that get triggered as a result of resize. This can be useful for differentiating the source of an event (for example, user-initiated or programmatically-triggered events).

Returns

Map: this

Example

// Resize the map when the map container is shown
// after being initially hidden with CSS.
var mapDiv = document.getElementById('map');
if (mapDiv.style.visibility === true) map.resize();

rotateTo(bearing, option?, eventData?)

Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Parameters

  • bearing(number)The desired bearing.

  • options(AnimationOptions?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

scrollZoom

The map's ScrollZoomHandler, which implements zooming in and out with a scroll wheel or trackpad. Find more details and examples using scrollZoom in the ScrollZoomHandler section.

setBearing(bearing, eventData?)

Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Equivalent to jumpTo({bearing: bearing}).

Parameters

  • bearing(number)The desired bearing.
  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// rotate the map to 90 degrees
map.setBearing(90);

setCenter(center, eventData?)

Sets the map's geographical centerpoint. Equivalent to jumpTo({center: center}).

Parameters

center(LngLatLike)The centerpoint to set.

eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

map.setCenter([-74, 38]);

setFeaturesState(feature, state)

Sets the state of a feature. A feature's state is a set of user-defined key-value pairs that are assigned to a feature at runtime. When using this method, the state object is merged with any existing key-value pairs in the feature's state. Features are identified by their feature.id attribute, which can be any number or string.

This method can only be used with sources that have a feature.id attribute. The feature.id attribute can be defined in three ways:

For vector or GeoJSON sources, including an id attribute in the original data file.

For vector or GeoJSON sources, using the promoteId option at the time the source is defined.

For GeoJSON sources, using the generateId option to auto-assign an id based on the feature's index in the source data. If you change feature data using map.getSource('some id').setData(..), you may need to re-apply state taking into account updated id values.

Note: You can use the feature-state expression to access the values in a feature's state object for the purposes of styling.

Parameters

feature(Object)Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.

Name Description
feature.id(string,number) Unique id of the feature.
feature.sourcestring The id of the vector or GeoJSON source for the feature.
feature.sourceLayerstring? (optional) For vector tile sources, sourceLayer is required.

state(Object)A set of key-value pairs. The values should be valid JSON types.

Example

// When the mouse moves over the `my-layer` layer, update
// the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', function(e) {
if (e.features.length > 0) {
map.setFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id,
}, {
hover: true
});
}
});

Related

  • Create a hover effect

setFilter(layerId, filter, options = {})

Sets the filter for the specified style layer.

Filters control which features a style layer renders from its source. Any feature for which the filter expression evaluates to true will be rendered on the map. Those that are false will be hidden.

Use setFilter to show a subset of your source data.

To clear the filter, pass null or undefined as the second parameter.

Parameters

layerId(string)The ID of the layer to which the filter will be applied. filter((Array | null | undefined))The filter, conforming to the vietmap Style Specification's filter definition . If null or undefined is provided, the function removes any existing filter from the layer. options(Object?)(default {})Options object.

Name Description
options.validatebooleandefault: true Whether to check if the filter conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Map: this

Example

// display only features with the 'name' property 'USA'
map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);


// display only features with five or more 'available-spots'
map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);


// remove the filter for the 'bike-docks' style layer
map.setFilter('bike-docks', null);

Related

  • Create a timeline animation

setLayerZoomRange(layerId, minzoom, maxzoom)

Sets the zoom extent for the specified style layer. The zoom extent includes the minimum zoom level and maximum zoom level) at which the layer will be rendered.

Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the minimum zoom level of the source layer because the data does not exist at those zoom levels. If the minimum zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style layer will not be rendered at all zoom levels in the zoom range.

Parameters

  • layerId(string)The ID of the layer to which the zoom extent will be applied.

  • minzoom(number)The minimum zoom to set (0-24).

  • maxzoom(number)The maximum zoom to set (0-24).

Returns

Map: this

Example

map.setLayerZoomRange('my-layer', 2, 5);

setLayoutProperty(layerId, name, value, options = {})

Sets the value of a layout property in the specified style layer.

Parameters

  • layerId(string)The ID of the layer to set the layout property in.

  • name(string)The name of the layout property to set.

  • value(any)The value of the layout property. Must be of a type appropriate for the property, as defined in the vietmap Style Specification .

Name Description
options(Object?)(default {}) Options object.
options.validatebooleandefault: true Options object.

Whether to check if value conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Map: this

Example

map.setLayoutProperty('my-layer', 'visibility', 'none');

setLight(light, options = {})

Sets the any combination of light values.

Parameters * light(LightSpecification)Light properties to set. Must conform to the vietmap Style Specification . * options(Object?)(default {})Options object.

Name Description
options.validatebooleandefault: true Whether to check if value conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Map: this

Example

var layerVisibility = map.getLayoutProperty('my-layer', 'visibility');

setMaxBounds(bounds)

Sets or clears the map's geographical bounds.

Pan and zoom operations are constrained within these bounds. If a pan or zoom is performed that would display regions outside these bounds, the map will instead display a position and zoom level as close as possible to the operation's request while still remaining within the bounds.

Parameters

bounds((LngLatBoundsLike | null | undefined))The maximum bounds to set. If null or undefined is provided, the function removes the map's maximum bounds.

Returns

Map: this

Example

// Define bounds that conform to the `LngLatBoundsLike` object.
var bounds = [
[-74.04728, 40.68392], // [west, south]
[-73.91058, 40.87764]  // [east, north]
];
// Set the map's max bounds.
map.setMaxBounds(bounds);

setMaxPitch(maxPitch)

Sets or clears the map's maximum pitch. If the map's current pitch is higher than the new maximum, the map will pitch to the new maximum.

Parameters

maxPitch((number | null | undefined))The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the vietmap project. If null or undefined is provided, the function removes the current maximum pitch (sets it to 60).

Returns

Map: this

setMaxZoom(maxZoom)

Sets or clears the map's maximum zoom level. If the map's current zoom level is higher than the new maximum, the map will zoom to the new maximum.

Parameters

maxZoom((number | null | undefined))The maximum zoom level to set. If null or undefined is provided, the function removes the current maximum zoom (sets it to 22).

Returns

Map: this

Example

map.setMaxZoom(18.75);

setMinPitch(minPitch)

Sets or clears the map's minimum pitch. If the map's current pitch is lower than the new minimum, the map will pitch to the new minimum.

Parameters

minPitch((number | null | undefined))The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the vietmap project. If null or undefined is provided, the function removes the current minimum pitch (i.e. sets it to 0).

Returns

Map: this

setMinZoom(minZoom)

Sets or clears the map's minimum zoom level. If the map's current zoom level is lower than the new minimum, the map will zoom to the new minimum.

It is not always possible to zoom out and reach the set minZoom. Other factors such as map height may restrict zooming. For example, if the map is 512px tall it will not be possible to zoom below zoom 0 no matter what the minZoom is set to.

Parameters

minZoom((number | null | undefined))The minimum zoom level to set (-2 - 24). If null or undefined is provided, the function removes the current minimum zoom (i.e. sets it to -2).

Returns

Map: this

Example

map.setMinZoom(12.25);

setPadding(padding, eventData?)

Sets the padding in pixels around the viewport.

Equivalent to jumpTo({padding: padding}).

Parameters

  • padding(PaddingOptions)The desired padding. Format: { left: number, right: number, top: number, bottom: number }
  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// Sets a left padding of 300px, and a top padding of 50px
map.setPadding({ left: 300, top: 50 });

setPaintProperty(layerId, name, value, options = {})

Sets the value of a paint property in the specified style layer.

Parameters

  • layerId(string)The ID of the layer to set the paint property in.

  • name(string)The name of the paint property to set.

  • value(any)The value of the paint property to set. Must be of a type appropriate for the property, as defined in the vietmap Style Specification .

options(Object?)(default {})Options object.

Name Description
options.validatebooleandefault: true Whether to check if value conforms to the vietmap GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.

Returns

Map: this

Example

map.setPaintProperty('my-layer', 'fill-color', '#faafee');

Related

  • Change a layer's color with buttons

  • Create a draggable point

setPitch(pitch, eventData?)

Sets the map's pitch (tilt). Equivalent to jumpTo({pitch: pitch}).

Parameters

  • pitch(number)The pitch to set, measured in degrees away from the plane of the screen (0-60).

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

setPixelRatio(pixelRatio)

Sets the map's pixel ratio. This allows to override devicePixelRatio. After this call, the canvas' width attribute will be container.clientWidth * pixelRatio and its height attribute will be container.clientHeight * pixelRatio.

Parameters

  • pixelRatio(number)The pixel ratio.

  • setRenderWorldCopies(renderWorldCopies)

  • Sets the state of renderWorldCopies.

Parameters

renderWorldCopies(boolean)If true , multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false :

When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude.

Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.

undefined is treated as true, null is treated as false.

Returns

Map: this

Example

map.setRenderWorldCopies(true);

Related

  • Render world copies

setStyle(style, options?)

Updates the map's vietmap style object with a new value.

If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites (images used for icons and patterns) and glyphs (fonts for label text) cannot be diffed. If the sprites or fonts used in the current style and the given style are different in any way, the map renderer will force a full update, removing the current style and building the given one from scratch.

Parameters

  • style((StyleSpecification | string | null))A JSON object conforming to the schema described in the vietmap Style Specification , or a URL to such JSON.

  • options(Object?)Options object.

Name Description
options.diffbooleandefault: true If false, force a 'full' update, removing the current style and building the given one instead of attempting a diff-based update.
options.localIdeographFontFamilystringdefault: 'sans-serif' Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set to false , to enable font settings from the map's style for these glyph ranges. Forces a full update.

Returns

Map: this

Example

map.setStyle("https://maps.vietmap.vn/mt/tm/style.json?apikey="your-apikey"");

setTransformRequest(transformRequest)

Updates the requestManager's transform request with a new function

Parameters

transformRequest(RequestTransformFunction)A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with a url property and optionally headers and credentials properties

Returns

Map: this

Example

map.setTransformRequest((url: string, resourceType: string) => {});

setZoom(zoom, eventData?)

Sets the map's zoom level. Equivalent to jumpTo({zoom: zoom}).

Parameters

  • zoom(number)The zoom level to set (0-20).

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// Zoom to the zoom level 5 without an animated transition
map.setZoom(5);

showCollisionBoxes

Gets and sets a Boolean indicating whether the map will render boxes around all symbols in the data source, revealing which symbols were rendered or which were hidden due to collisions. This information is useful for debugging.

showPadding

Gets and sets a Boolean indicating whether the map will visualize the padding offsets

showTileBoundaries

Gets and sets a Boolean indicating whether the map will render an outline around each tile and the tile ID. These tile boundaries are useful for debugging.

The uncompressed file size of the first vector source is drawn in the top left corner of each tile, next to the tile ID.

Example

map.showTileBoundaries = true;

snapToNorth(option?, eventData?)

Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the bearingSnap threshold).

Parameters

  • options(AnimationOptions?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Stop

Stops any animated transition underway.

Returns

Map: this

touchPitch

The map's TouchPitchHandler, which allows the user to pitch the map with touch gestures. Find more details and examples using touchPitch in the TouchPitchHandler section.

touchZoomRotate

The map's TouchZoomRotateHandler, which allows the user to zoom or rotate the map with touch gestures. Find more details and examples using touchZoomRotate in the TouchZoomRotateHandler section.

triggerRepaint()

Trigger the rendering of a single frame. Use this method with custom layers to repaint the map when the layer changes. Calling this multiple times before the next frame is rendered will still result in only a single frame being rendered.

Example

map.triggerRepaint();

Related

  • Add a 3D model

  • Add an animated icon to the map

unproject(point)

Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.

Parameters

point(PointLike)The pixel coordinates to unproject.

Returns

LngLat: The LngLat corresponding to point .

Example

map.on('click', function(e) {
// When the map is clicked, get the geographic coordinate.
var coordinate = map.unproject(e.point);
});

updateImage(id, image)

Update an existing image in a style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with icon-image, background-pattern, fill-pattern, or line-pattern.

Parameters

  • id(string)The ID of the image.

  • image((HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface))The image as an HTMLImageElement , ImageData , ImageBitmap or object with width , height , and data properties with the same format as ImageData .

Example

// If an image with the ID 'cat' already exists in the style's sprite,
// replace that image with a new image, 'other-cat-icon.png'.
if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');

zoomIn(options?, eventData?)

Increases the map's zoom level by 1.

Parameters

  • options(AnimationOptions?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// zoom the map in one level with a custom animation duration
map.zoomIn({duration: 1000});

zoomOut(option?, eventData?)

Decreases the map's zoom level by 1.

Parameters

options(AnimationOptions?)Options object

eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// zoom the map out one level with a custom animation offset
map.zoomOut({offset: [80, 60]});

zoomTo(zoom, option?, eventData?)

Zooms the map to the specified zoom level, with an animated transition.

Parameters

  • zoom(number)The zoom level to transition to.

  • options((AnimationOptions | null)?)Options object

  • eventData(any?)Additional properties to be added to event objects of events triggered by this method.

Returns

Map: this

Example

// Zoom to the zoom level 5 without an animated transition
map.zoomTo(5);
// Zoom to the zoom level 8 with an animated transition
map.zoomTo(8, {
duration: 2000,
offset: [100, 50]
});

Events

boxzoomcancel

Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. See BoxZoomHandler.

Properties

data(vietmapZoomEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// the user cancels a "box zoom" interaction.
map.on('boxzoomcancel', function() {
console.log('A boxzoomcancel event occurred.');
});

boxzoomend

Fired when a "box zoom" interaction ends. See BoxZoomHandler.

Properties

data(vietmapZoomEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after a "box zoom" interaction ends.
map.on('boxzoomend', function() {
console.log('A boxzoomend event occurred.');
});

boxzoomstart

Fired when a "box zoom" interaction starts. See BoxZoomHandler.

Properties

data(vietmapZoomEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before a "box zoom" interaction starts.
map.on('boxzoomstart', function() {
console.log('A boxzoomstart event occurred.');
});

click

Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the point that is pressed and released contains a visible portion of the specifed layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('click', function(e) {
console.log('A click event has occurred at ' + e.lngLat);
});


// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('click', 'poi-label', function(e) {
console.log('A click event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);
});

Related

  • Measure distances

  • Center the map on a clicked symbol

contextmenu

Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the right mouse button is
// pressed within the map.
map.on('contextmenu', function() {
console.log('A contextmenu event occurred.');
});

data

Fired when any map data loads or changes. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when map data loads or changes.
map.on('data', function() {
console.log('A data event occurred.');
});

Related

  • Display HTML clusters with custom properties

dataabort

Fired when a request for one of the map's sources' tiles is aborted. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a request for one of the map's sources' tiles is aborted.
map.on('dataabort', function() {
console.log('A dataabort event occurred.');
});

dataloading

Fired when any map data (style, source, tile, etc) begins loading or changing asyncronously. All dataloading events are followed by a data, dataabort or error event. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when any map data begins loading
// or changing asynchronously.
map.on('dataloading', function() {
console.log('A dataloading event occurred.');
});

dbclick

Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the point that is clicked twice contains a visible portion of the specifed layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('dblclick', function(e) {
console.log('A dblclick event has occurred at ' + e.lngLat);
});


// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('dblclick', 'poi-label', function(e) {
console.log('A dblclick event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);
});

drag

Fired repeatedly during a "drag to pan" interaction. See DragPanHandler.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// repeatedly  during a "drag to pan" interaction.
map.on('drag', function() {
console.log('A drag event occurred.');
});

dragend

Fired when a "drag to pan" interaction ends. See DragPanHandler.

Properties

data({originalEvent: DragEvent})

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a "drag to pan" interaction ends.
map.on('dragend', function() {
console.log('A dragend event occurred.');
});

Related

  • Create a draggable marker

dragstart

Fired wh+en a "drag to pan" interaction starts. See DragPanHandler.

Properties

data({originalEvent: DragEvent})

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a "drag to pan" interaction starts.
map.on('dragstart', function() {
console.log('A dragstart event occurred.');
});

error

Fired when an error occurs. This is GL JS's primary error reporting mechanism. We use an event instead of throw to better accommodate asyncronous operations. If no listeners are bound to the error event, the error will be printed to the console.

Properties

data({error: {message: string}})

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when an error occurs.
map.on('error', function() {
console.log('A error event occurred.');
});

idle

Fired after the last frame rendered before the map enters an "idle" state:

No camera transitions are in progress

All currently requested tiles have loaded

All fade/transition animations have completed

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before the map enters an "idle" state.
map.on('idle', function() {
console.log('A idle event occurred.');
});

load

Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the map has finished loading.
map.on('load', function() {
console.log('A load event occurred.');
});

Related

  • Draw GeoJSON points

  • Add live realtime data

  • Animate a point

mousedown

Fired when a pointing device (usually a mouse) is pressed within the map.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the the cursor is pressed while inside a visible portion of the specifed layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('mousedown', function() {
console.log('A mousedown event has occurred.');
});


// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mousedown', 'poi-label', function() {
console.log('A mousedown event has occurred on a visible portion of the poi-label layer.');
});

Related

  • Create a draggable point

mouseenter

Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from outside that layer or outside the map canvas.

Important: This event can only be listened for when Map#on includes three arguments, where the second argument specifies the desired layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('mouseenter', 'water', function() {
console.log('A mouseenter event occurred on a visible portion of the water layer.');
});

Related

  • Center the map on a clicked symbol

  • Display a popup on click

mouseleave

Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves the map canvas.

Important: This event can only be listened for when Map#on includes three arguements, where the second argument specifies the desired layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the pointing device leaves
// a visible portion of the specified layer.
map.on('mouseleave', 'water', function() {
console.log('A mouseleave event occurred.');
});

Related

  • Highlight features under the mouse pointer

  • Display a popup on click

mousemove

Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. As you move the cursor across the map, the event will fire every time the cursor changes position within the map.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the the cursor is inside a visible portion of the specified layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('mousemove', function() {
console.log('A mousemove event has occurred.');
});


// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mousemove', 'poi-label', function() {
console.log('A mousemove event has occurred on a visible portion of the poi-label layer.');
});

Related

  • Get coordinates of the mouse pointer

  • Highlight features under the mouse pointer

  • Display a popup on over

mouseout

Fired when a point device (usually a mouse) leaves the map's canvas.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the pointing device leave's
// the map's canvas.
map.on('mouseout', function() {
console.log('A mouseout event occurred.');
});

mouseover

Fired when a pointing device (usually a mouse) is moved within the map. As you move the cursor across a web page containing a map, the event will fire each time it enters the map or any child elements.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the the cursor is moved inside a visible portion of the specifed layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('mouseover', function() {
console.log('A mouseover event has occurred.');
});

```javascript
// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mouseover', 'poi-label', function() {
console.log('A mouseover event has occurred on a visible portion of the poi-label layer.');
});

Related

  • Get coordinates of the mouse pointer

  • Highlight features under the mouse pointer

  • Display a popup on hover

mouseup

Fired when a pointing device (usually a mouse) is released within the map.

Note: This event is compatible with the optional layerId parameter. If layerId is included as the second argument in Map#on, the event listener will fire only when the the cursor is released while inside a visible portion of the specifed layer.

Properties

data(MapMouseEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener
map.on('mouseup', function() {
console.log('A mouseup event has occurred.');
});


// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mouseup', 'poi-label', function() {
console.log('A mouseup event has occurred on a visible portion of the poi-label layer.');
});

Related

Create a draggable point

move

Fired repeatedly during an animated transition from one view to another, as the result of either user interaction or methods such as Map#flyTo.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during an animated transition.
map.on('move', function() {
console.log('A move event occurred.');
});

Related

  • Display HTML clusters with custom properties

moveend

Fired just after the map completes a transition from one view to another, as the result of either user interaction or methods such as Map#jumpTo.

Properties

data({originalEvent: DragEvent})

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after the map completes a transition.
map.on('moveend', function() {
console.log('A moveend event occurred.');
});

Related

Display HTML clusters with custom properties

movestart

Fired just before the map begins a transition from one view to another, as the result of either user interaction or methods such as Map#jumpTo.

Properties

data({originalEvent: DragEvent})

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before the map begins a transition
// from one view to another.
map.on('movestart', function() {
console.log('A movestart` event occurred.');
});

pitch

Fired repeatedly during the map's pitch (tilt) animation between one state and another as the result of either user interaction or methods such as Map#flyTo.

Properties

data(MapEventData)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during a pitch (tilt) transition.
map.on('pitch', function() {
console.log('A pitch event occurred.');
});

pitchend

Fired immediately after the map's pitch (tilt) finishes changing as the result of either user interaction or methods such as Map#flyTo.

Properties

data(MapEventData)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after a pitch (tilt) transition ends.
map.on('pitchend', function() {
console.log('A pitchend event occurred.');
});

pitchstart

Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as Map#flyTo .

Properties

data(MapEventData)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before a pitch (tilt) transition starts.
map.on('pitchstart', function() {
console.log('A pitchstart event occurred.');
});

remove

Fired immediately after the map has been removed with Map.event:remove.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after the map is removed.
map.on('remove', function() {
console.log('A remove event occurred.');
});

render

Fired whenever the map is drawn to the screen, as the result of

a change to the map's position, zoom, pitch, or bearing

a change to the map's style

a change to a GeoJSON source

the loading of a vector tile, GeoJSON file, glyph, or sprite

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// whenever the map is drawn to the screen.
map.on('render', function() {
console.log('A render event occurred.');
});

resize

Fired immediately after the map has been resized.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// immediately after the map has been resized.
map.on('resize', function() {
console.log('A resize event occurred.');
});

rotate

Fired repeatedly during a "drag to rotate" interaction. See DragRotateHandler.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during "drag to rotate" interaction.
map.on('rotate', function() {
console.log('A rotate event occurred.');
});

roteteend

Fired when a "drag to rotate" interaction ends. See DragRotateHandler.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after a "drag to rotate" interaction ends.
map.on('rotateend', function() {
console.log('A rotateend event occurred.');
});

rotatestart

Fired when a "drag to rotate" interaction starts. See DragRotateHandler.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before a "drag to rotate" interaction starts.
map.on('rotatestart', function() {
console.log('A rotatestart event occurred.');
});

sourcedata

Fired when one of the map's sources loads or changes, including if a tile belonging to a source loads or changes. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when one of the map's sources loads or changes.
map.on('sourcedata', function() {
console.log('A sourcedata event occurred.');
});

sourcedataabort

Fired when a request for one of the map's sources' tiles is aborted. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a request for one of the map's sources' tiles is aborted.
map.on('sourcedataabort', function() {
console.log('A sourcedataabort event occurred.');
});

sourcedataloading

Fired when one of the map's sources begins loading or changing asyncronously. All sourcedataloading events are followed by a sourcedata, sourcedataabort or error event. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// map's sources begin loading or
// changing asyncronously.
map.on('sourcedataloading', function() {
console.log('A sourcedataloading event occurred.');
});

styledata

Fired when the map's style loads or changes. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the map's style loads or changes.
map.on('styledata', function() {
console.log('A styledata event occurred.');
});

styledataloading

Fired when the map's style begins loading or changing asyncronously. All styledataloading events are followed by a styledata or error event. See MapDataEvent for more information.

Properties

data(MapDataEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// map's style begins loading or
// changing asyncronously.
map.on('styledataloading', function() {
console.log('A styledataloading event occurred.');
});

styleimagemissing

Fired when an icon or pattern needed by the style is missing. The missing image can be added with Map#addImage within this event listener callback to prevent the image from being skipped. This event can be used to dynamically generate icons and patterns.

Properties

id(string): The id of the missing image.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// an icon or pattern is missing.
map.on('styleimagemissing', function() {
console.log('A styleimagemissing event occurred.');
});

Related

Generate and add a missing icon to the map

touchcancel

Fired when a touchcancel event occurs within the map.

Properties

data(MapTouchEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a touchcancel event occurs within the map.
map.on('touchcancel', function() {
console.log('A touchcancel event occurred.');
});

touchend

Fired when a touchend event occurs within the map.

Properties

data(MapTouchEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a touchstart event occurs within the map.
map.on('touchstart', function() {
console.log('A touchstart event occurred.');
});

Related

Create a draggable point

touchmove

Fired when a touchmove event occurs within the map.

Properties

data(MapTouchEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a touchmove event occurs within the map.
map.on('touchmove', function() {
console.log('A touchmove event occurred.');
});

Related

Create a draggable point

touchstart

Fired when a touchstart event occurs within the map.

Properties

data(MapTouchEvent): // Initialize the map var map = new vietmapgl.Map({ // map options }); // Set an event listener that fires // when a touchstart event occurs within the map. map.on('touchstart', function() { console.log('A touchstart event occurred.'); });

Related

Create a draggable point

webglcontextlost

Fired when the WebGL context is lost.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the WebGL context is lost.
map.on('webglcontextlost', function() {
console.log('A webglcontextlost event occurred.');
});

webglcontextrestored

Fired when the WebGL context is restored.

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when the WebGL context is restored.
map.on('webglcontextrestored', function() {
console.log('A webglcontextrestored event occurred.');
});

wheel

Fired when a wheel event occurs within the map.

Properties

data(MapWheelEvent)

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// when a wheel event occurs within the map.
map.on('wheel', function() {
console.log('A wheel event occurred.');
});

zoom

Fired repeatedly during an animated transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during a zoom transition.
map.on('zoom', function() {
console.log('A zoom event occurred.');
});

zoomend

Fired just after the map completes a transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just after a zoom transition finishes.
map.on('zoomend', function() {
console.log('A zoomend event occurred.');
});

zoomstart

Fired just before the map begins a transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.

Properties

data((MapMouseEvent | MapTouchEvent))

Example

// Initialize the map
var map = new vietmapgl.Map({ // map options });
// Set an event listener that fires
// just before a zoom transition starts.
map.on('zoomstart', function() {
console.log('A zoomstart event occurred.');
});

Display a map