Interactive map and support classes.
Map
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 the JavaScript Maps SDK initializes the map on the page and returns your
Map
object.
new Map(options: Object)
Extends Evented
Parameters
options
(Object)
Name | Type | Description |
---|---|---|
options.container |
(HTMLElement | string)
|
The HTML element in which the JavaScript Maps SDK will render the
map, or the element's string
id
. The specified element must have no children.
|
options.minZoom |
number
(default: 0 )
|
The minimum zoom level of the map (0-24). |
options.maxZoom |
number
(default: 22 )
|
The maximum zoom level of the map (0-24). |
options.minPitch |
number
(default: 0 )
|
The minimum pitch of the map (0-60). |
options.maxPitch |
number
(default: 60 )
|
The maximum pitch of the map (0-60). |
options.style |
(Object | string | Common.Style)?
|
The map's style. |
options.region |
Common.Region?
|
The map's region. |
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.interactive |
boolean
(default: true )
|
If
false
, no mouse, touch, or keyboard listeners will be attached to the
map, so it will not respond to interaction.
|
options.bearingSnap |
number
(default: 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.pitchWithRotate |
boolean
(default: true )
|
If
false
, the map's pitch (tilt) control with "drag to rotate" interaction
will be disabled.
|
options.attributionControl |
boolean
(default: true )
|
If
true
, an
AttributionControl
will be added to the map.
|
options.logoPosition |
string
(default: 'bottom-left' )
|
A string representing the position of the Trimble Maps 2.0 wordmark
on the map. Valid options are
top-left
,
top-right
,
bottom-left
,
bottom-right
.
|
options.failIfMajorPerformanceCaveat |
boolean
(default: false )
|
If
true
, map creation will fail if the performance of Trimble Maps 2.0
JS API would be dramatically worse than expected (i.e. a software
renderer would be used).
|
options.preserveDrawingBuffer |
boolean
(default: 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.antialias |
boolean?
|
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.refreshExpiredTiles |
boolean
(default: true )
|
If
false
, the map won't attempt to re-request tiles once they expire per
their HTTP
cacheControl
/
expires
headers.
|
options.maxBounds |
LngLatBoundsLike?
|
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.boxZoom |
boolean
(default: true )
|
If
true
, the "box zoom" interaction is enabled (see
BoxZoomHandler
).
|
options.dragRotate |
boolean
(default: 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.keyboard |
boolean
(default: true )
|
If
true
, keyboard shortcuts are enabled (see
KeyboardHandler
).
|
options.doubleClickZoom |
boolean
(default: 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.trackResize |
boolean
(default: true )
|
If
true
, the map will automatically resize when the browser window resizes.
|
options.center |
LngLatLike
(default: [0,0] )
|
The initial geographical centerpoint of the map. If
center
is not specified in the constructor options, the JavaScript Maps SDK
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: The JavaScript Maps SDK uses longitude, latitude coordinate
order (as opposed to latitude, longitude) to match GeoJSON.
|
options.zoom |
number
(default: 0 )
|
The initial zoom level of the map. If
zoom
is not specified in the constructor options, the JavaScript Maps SDK
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.bearing |
number
(default: 0 )
|
The initial bearing (rotation) of the map, measured in degrees
counter-clockwise from north. If
bearing
is not specified in the constructor options, the JavaScript Maps SDK
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.pitch |
number
(default: 0 )
|
The initial pitch (tilt) of the map, measured in degrees away from
the plane of the screen (0-60). If
pitch
is not specified in the constructor options, the JavaScript Maps SDK
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.bounds |
LngLatBoundsLike?
|
The initial bounds of the map. If
bounds
is specified, it overrides
center
and
zoom
constructor options.
|
options.fitBoundsOptions |
Object?
|
A
Map#fitBounds
options object to use
only
when fitting the initial
bounds
provided above.
|
options.renderWorldCopies |
boolean
(default: true )
|
If
true
, multiple copies of the world will be rendered side by side beyond
-180 and 180 degrees longitude. If set to
false
:
|
options.maxTileCacheSize |
number
(default: 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.localIdeographFontFamily |
string
(default: '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.
|
options.transformRequest |
RequestTransformFunction
(default: 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.collectResourceTiming |
boolean
(default: 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.fadeDuration |
number
(default: 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.crossSourceCollisions |
boolean
(default: 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.locale |
Object
(default: 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.satelliteProvider |
Common.SatelliteProvider?
|
satellite source provider.Only supports Satellite style and will be ignored for all others. |
Example
var map = new TrimbleMaps.Map({
container: 'map',
center: new TrimbleMaps.LngLat(-122.420679, 37.772537),
zoom: 13,
style: TrimbleMaps.Common.Style.TRANSPORTATION,
hash: true
});
Instance Members
Adds an IControl to the map, calling
control.onAdd(this)
.
addControl(control: IControl, position: string?): Map
Parameters
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 TrimbleMaps.NavigationControl());
Removes the control from the map.
removeControl(control: IControl): Map
Parameters
Returns
Map
:
this
Example
// Define a new navigation control.
var navigation = new TrimbleMaps.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Remove zoom and rotation controls from the map.
map.removeControl(navigation);
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.
resize(eventData: Object?): Map
Parameters
eventData
(Object?)
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();
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.
getBounds(): LngLatBounds
Returns
LngLatBounds
:
The geographical bounds of the map as
LngLatBounds
.
Example
var bounds = map.getBounds();
Returns the maximum geographical bounds the map is constrained to, or
null
if none set.
getMaxBounds(): (LngLatBounds | null)
Returns
(LngLatBounds | null)
:
The map object.
Example
var maxBounds = map.getMaxBounds();
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.
setMaxBounds(bounds: (LngLatBoundsLike | null | undefined)): Map
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);
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.
setMinZoom(minZoom: (number | null | undefined)): Map
Parameters
Returns
Map
:
this
Example
map.setMinZoom(12.25);
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.
getRenderWorldCopies(): boolean
Returns
boolean
:
renderWorldCopies
Example
var worldCopiesRendered = map.getRenderWorldCopies();
Sets the state of renderWorldCopies
.
setRenderWorldCopies(renderWorldCopies: boolean): Map
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);
Returns a Point representing pixel coordinates,
relative to the map's container
,
that correspond to the specified geographical location.
project(lnglat: LngLatLike): Point
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);
Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.
unproject(point: PointLike): LngLat
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);
});
Adds a listener for events of a specified type, optionally limited to features in a specified style layer.
on(type: string, layerId: string, listener: Function): Map
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 |
dblclick
|
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
|
layerId
(string)
(optional) The ID of a style layer. 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
layerId
is not supplied, the event will not have a
features
property.
Please note that many event types are not compatible with the
optional
layerId
parameter.
listener
(Function)
The function to be called when the event is fired.
Returns
Map
:
this
Adds a listener that will be called only once to a specified event type.
once(type: string, listener: Function): Map
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
Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer.
once(type: string, layerId: string, listener: Function): Map
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.
layerId
(string)
The ID of a style layer. 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.
listener
(Function)
The function to be called when the event is fired.
Returns
Map
:
this
Removes an event listener for layer-specific events previously added with
Map#on
.
off(type: string, layerId: string, listener: Function): Map
Parameters
type
(string)
The event type previously used to install the listener.
layerId
(string)
The layer ID previously used to install the listener.
listener
(Function)
The function previously installed as a listener.
Returns
Map
:
this
Returns an array of GeoJSON Feature objects representing visible features that satisfy the query parameters.
queryRenderedFeatures(geometry: (PointLike | Array<PointLike>)?, options: Object?): Array<Object>
Parameters
geometry
((PointLike | Array<PointLike>)?)
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 | Type | Description |
---|---|---|
options.layers |
Array<string>?
|
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.filter |
Array?
|
A filter to limit query results. |
options.validate |
boolean
(default: true )
|
Whether to check if the [options.filter] conforms to the Mapbox 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<Object>
:
An array of
GeoJSON
feature
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 a top-level layer
property whose value
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'] });
Returns an array of GeoJSON Feature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
querySourceFeatures(sourceId: string, parameters: Object?): Array<Object>
Parameters
sourceId
(string)
The ID of the vector tile or GeoJSON source to query.
parameters
(Object?)
Options object.
Name | Type | Description |
---|---|---|
parameters.sourceLayer |
string?
|
The name of the [source layer] to query. For vector tile sources, this parameter is required. For GeoJSON sources, it is ignored. |
parameters.filter |
Array?
|
A [filter] to limit query results. |
parameters.validate |
boolean
(default: true )
|
Whether to check if the [parameters.filter] conforms to the Mapbox 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<Object>
:
An array of
GeoJSON
Feature
objects
.
In contrast to Map#queryRenderedFeatures, this function returns all features matching the query parameters, whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently visible viewport.
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'
});
Updates the map's 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.
setStyle(style: (Object | string | Common.Style), options: Object?): Map
Parameters
style
((Object | string | Common.Style))
The map's style.
options
(Object?)
Options object.
Name | Type | Description |
---|---|---|
options.diff |
boolean
(default: true )
|
If false, force a 'full' update, removing the current style and building the given one instead of attempting a diff-based update. |
options.satelliteProvider |
SatelliteProviderEnum?
|
satellite source provider.Only supports Satellite style and will be ignored for all others. |
options.localIdeographFontFamily |
string
(default:
'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(TrimbleMaps.Common.Style.TRANSPORTATION);
Set the map's region using TrimbleMaps.Common.Region enumeration.
setRegion(region: Common.Region): Map
Parameters
region
(Common.Region)
The map's region.
Returns
Map
:
this
Returns the map's region.
getRegion(): Common.Region
Returns
Common.Region
:
The map's region.
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
.
isSourceLoaded(id: string): boolean
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');
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.
getSource(id: string): Object?
Parameters
id
(string)
The ID of the source to get.
Returns
Object?
:
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.
var sourceObject = map.getSource('points');
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.
addImage(id: string, image: (HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface), options: $Shape<StyleImageMetadata>)
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
($Shape<StyleImageMetadata>
= {}
)
Options object.
Name | Type | Description |
---|---|---|
options.pixelRatio |
any
(default: 1 )
|
The ratio of pixels in the image to physical pixels on the screen |
options.sdf |
any
(default: false )
|
Whether the image should be interpreted as an SDF image |
options.stretchX |
any
|
[[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.stretchY |
any
|
[[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.content |
any
|
[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
// 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
});
}
});
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
].
updateImage(id: string, image: (HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface))
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');
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.
hasImage(id: string): boolean
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');
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.
removeImage(id: string)
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');
Load an image from an external URL to be used with Map#addImage. External domains must support CORS.
loadImage(url: string, callback: Function)
Parameters
url
(string)
The URL of the image file. Image file must be in png, webp, or
jpg format.
callback
(Function)
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);
});
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.
listImages(): Array<string>
Returns
Array<string>
:
An Array of strings containing the names of all sprites/images currently
available in the map.
Example
var allImages = map.listImages();
Adds a [Mapbox 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 [Mapbox Style Specification].
addLayer(layer: (Object | CustomLayerInterface), beforeId: string?): Map
Parameters
layer
((Object | CustomLayerInterface))
The layer to add, conforming to either the Mapbox Style
Specification's
[layer definition]
or, less commonly, the
CustomLayerInterface
specification.
The Mapbox Style Specification's layer definition is appropriate
for most layers.
Name | Type | Description |
---|---|---|
layer.id |
string
|
A unique identifier that you define. |
layer.type |
string
|
The type of layer (for example
fill
or
symbol
).
A list of layer types is available in the
[Mapbox Style Specification]
.
(This can also be |
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
[Mapbox Style Specification]
) directly.
This is
required
for all
layer.type
options
except
for
custom
.
|
layer.sourceLayer |
string?
|
(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.filter |
array?
|
(optional) An expression specifying conditions on
source features.
Only features that match the filter are displayed.
The Mapbox 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.paint |
Object?
|
(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
[Mapbox Style Specification]
.
If no paint properties are specified, default values
will be used.
|
layer.layout |
Object?
|
(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
[Mapbox Style Specification]
.
If no layout properties are specified, default
values will be used.
|
layer.maxzoom |
number?
|
(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.minzoom |
number?
|
(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.metadata |
Object?
|
(optional) Arbitrary properties useful to track with the layer, but do not influence rendering. |
layer.renderingMode |
string?
|
This is only applicable for layers with the type
custom
.
See
CustomLayerInterface
for more information.
|
beforeId
(string?)
The ID of an existing layer to insert the new layer before,
resulting in the new layer appearing visually beneath the
existing layer.
If this argument is not specified, the layer will be appended to
the end of the layers array
and appear visually above all other layers.
Returns
Map
:
this
Moves a layer to a different z-position.
moveLayer(id: string, beforeId: string?): Map
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');
Removes the layer with the given ID from the map's style.
If no such layer exists, an error
event is fired.
removeLayer(id: string)
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');
Returns the layer with the specified ID in the map's style.
getLayer(id: string): Object?
Parameters
id
(string)
The ID of the layer to get.
Returns
Object?
:
The layer with the specified ID, or
undefined
if the ID corresponds to no existing layers.
Example
var stateDataLayer = map.getLayer('state-data');
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.
setFilter(layerId: string, filter: (Array | null | undefined), options: Object?): Map
Parameters
layerId
(string)
The ID of the layer to which the filter will be applied.
options
(Object?
= {}
)
Options object.
Name | Type | Description |
---|---|---|
options.validate |
boolean
(default: true )
|
Whether to check if the filter conforms to the map 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);
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.
setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): Map
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);
Sets the value of a paint property in the specified style layer.
setPaintProperty(layerId: string, name: string, value: any, options: Object?): Map
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 style.
options
(Object?
= {}
)
Options object.
Name | Type | Description |
---|---|---|
options.validate |
boolean
(default: true )
|
Whether to check if
value
conforms to the Mapbox 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');
Returns the value of a paint property in the specified style layer.
getPaintProperty(layerId: string, name: string): any
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.
Sets the value of a layout property in the specified style layer.
setLayoutProperty(layerId: string, name: string, value: any, options: Object?): Map
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 style.
options
(Object?
= {}
)
Options object.
Name | Type | Description |
---|---|---|
options.validate |
boolean
(default: true )
|
Whether to check if
value
conforms to the Mapbox 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');
Returns the value of a layout property in the specified style layer.
getLayoutProperty(layerId: string, name: string): any
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.
Sets the any combination of light values.
setLight(light: LightSpecification, options: Object?): Map
Parameters
light
(LightSpecification)
Light properties to set. Must conform to the
[Mapbox Style Specification]
.
options
(Object?
= {}
)
Options object.
Name | Type | Description |
---|---|---|
options.validate |
boolean
(default: true )
|
Whether to check if the filter conforms to the Mapbox 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');
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 anid
based on the feature's index in the source data. If you change feature data usingmap.getSource('some id').setData(..)
, you may need to re-apply state taking into account updatedid
values.
Note: You can use the [feature-state
expression] to
access the values in a feature's state object for the purposes of
styling.
setFeatureState(feature: Object, state: Object)
Parameters
feature
(Object)
Feature identifier. Feature objects returned from
Map#queryRenderedFeatures
or event handlers can be used as feature identifiers.
Name | Type | Description |
---|---|---|
feature.id |
(string | number)
|
Unique id of the feature. |
feature.source |
string
|
The id of the vector or GeoJSON source for the feature. |
feature.sourceLayer |
string?
|
(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
});
}
});
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.
removeFeatureState(target: Object, key: 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 | Type | Description |
---|---|---|
target.id |
(string | number)
|
(optional) Unique id of the feature. Optional if key is not specified. |
target.source |
string
|
The id of the vector or GeoJSON source for the feature. |
target.sourceLayer |
string?
|
(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');
});
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].
getFeatureState(feature: Object): Object
Parameters
feature
(Object)
Feature identifier. Feature objects returned from
Map#queryRenderedFeatures
or event handlers can be used as feature identifiers.
Name | Type | Description |
---|---|---|
feature.id |
(string | number)
|
Unique id of the feature. |
feature.source |
string
|
The id of the vector or GeoJSON source for the feature. |
feature.sourceLayer |
string?
|
(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
});
}
});
Returns the map's containing HTML element.
getContainer(): HTMLElement
Returns
HTMLElement
:
The map's container.
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.
getCanvasContainer(): HTMLElement
Returns
HTMLElement
:
The container of the map's
<canvas>
.
Returns the map's <canvas>
element.
getCanvas(): HTMLCanvasElement
Returns
HTMLCanvasElement
:
The map's
<canvas>
element.
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.
remove()
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.
triggerRepaint()
Example
map.triggerRepaint();
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.
showTileBoundaries
Type: boolean
Example
map.showTileBoundaries = true;
Gets and sets a Boolean indicating whether the map will visualize the padding offsets.
showPadding
Type: boolean
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.
showCollisionBoxes
Type: boolean
Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance.
repaint
Type: boolean
The version of map JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.
version
Type: string
Sets the map's geographical centerpoint. Equivalent to
jumpTo({center: center})
.
setCenter(center: LngLatLike, eventData: Object?): Map
Parameters
center
(LngLatLike)
The centerpoint to set.
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Example
map.setCenter([-74, 38]);
Pans the map by the specified offset.
panBy(offset: PointLike, options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Pans the map to the specified location with an animated transition.
panTo(lnglat: LngLatLike, options: AnimationOptions?, eventData: Object?): Map
Parameters
lnglat
(LngLatLike)
The location to pan the map to.
options
(AnimationOptions?)
Options describing the destination and animation of the
transition.
eventData
(Object?)
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});
Sets the map's zoom level. Equivalent to
jumpTo({zoom: zoom})
.
setZoom(zoom: number, eventData: Object?): Map
Parameters
zoom
(number)
The zoom level to set (0-20).
eventData
(Object?)
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);
Zooms the map to the specified zoom level, with an animated transition.
zoomTo(zoom: number, options: AnimationOptions?, eventData: Object?): Map
Parameters
zoom
(number)
The zoom level to transition to.
options
(AnimationOptions?)
Options object
eventData
(Object?)
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]
});
Increases the map's zoom level by 1.
zoomIn(options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
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});
Decreases the map's zoom level by 1.
zoomOut(options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
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]});
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})
.
setBearing(bearing: number, eventData: Object?): Map
Parameters
bearing
(number)
The desired bearing.
eventData
(Object?)
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);
Returns the current padding applied around the map viewport.
getPadding(): PaddingOptions
Returns
PaddingOptions
:
The current padding around the map viewport.
Sets the padding in pixels around the viewport.
Equivalent to jumpTo({padding: padding})
.
setPadding(padding: PaddingOptions, eventData: Object?): Map
Parameters
padding
(PaddingOptions)
The desired padding. Format: { left: number, right: number, top:
number, bottom: number }
eventData
(Object?)
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 });
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.
rotateTo(bearing: number, options: AnimationOptions?, eventData: Object?): Map
Parameters
bearing
(number)
The desired bearing.
options
(AnimationOptions?)
Options object
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Rotates the map so that north is up (0° bearing), with an animated transition.
resetNorth(options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.
resetNorthPitch(options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
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).
snapToNorth(options: AnimationOptions?, eventData: Object?): Map
Parameters
options
(AnimationOptions?)
Options object
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Sets the map's pitch (tilt). Equivalent to
jumpTo({pitch: pitch})
.
setPitch(pitch: number, eventData: Object?): Map
Parameters
pitch
(number)
The pitch to set, measured in degrees away from the plane of the
screen (0-60).
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
cameraForBounds(bounds: LngLatBoundsLike, options: CameraOptions?): (CameraOptions | void)
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
(CameraOptions?)
Options object
Name | Type | Description |
---|---|---|
options.padding |
(number | PaddingOptions)?
|
The amount of padding in pixels to add to the given bounds. |
options.offset |
PointLike
(default: [0,0] )
|
The center of the given bounds relative to the map's center, measured in pixels. |
options.maxZoom |
number?
|
The maximum zoom level to allow when the camera would transition to the specified bounds. |
Returns
(CameraOptions | void)
:
If map is able to fit to provided bounds, returns
CameraOptions
with
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}
});
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.
fitBounds(bounds: LngLatBoundsLike, options: Object?, eventData: Object?): Map
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
(Object?)
Options supports all properties from
AnimationOptions
and
CameraOptions
in addition to the fields below.
Name | Type | Description |
---|---|---|
options.padding |
(number | PaddingOptions)?
|
The amount of padding in pixels to add to the given bounds. |
options.linear |
boolean
(default: 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.easing |
Function?
|
An easing function for the animated transition. See AnimationOptions . |
options.offset |
PointLike
(default: [0,0] )
|
The center of the given bounds relative to the map's center, measured in pixels. |
options.maxZoom |
number?
|
The maximum zoom level to allow when the map view transitions to the specified bounds. |
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
Example
var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
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.
fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options: any?, eventData: Object?): Map
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
(any?)
Options object
Name | Type | Description |
---|---|---|
options.padding |
(number | PaddingOptions)?
|
The amount of padding in pixels to add to the given bounds. |
options.linear |
boolean
(default: 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.easing |
Function?
|
An easing function for the animated transition. See AnimationOptions . |
options.offset |
PointLike
(default: [0,0] )
|
The center of the given bounds relative to the map's center, measured in pixels. |
options.maxZoom |
number?
|
The maximum zoom level to allow when the map view transitions to the specified bounds. |
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
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}
});
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
.
jumpTo(options: CameraOptions, eventData: Object?): Map
Parameters
options
(CameraOptions)
Options object
eventData
(Object?)
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
});
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
.
easeTo(options: any, eventData: Object?): Map
Parameters
options
(any)
Options describing the destination and animation of the
transition.
Accepts
CameraOptions
and
AnimationOptions
.
eventData
(Object?)
Additional properties to be added to event objects of events
triggered by this method.
Returns
Map
:
this
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
.
flyTo(options: Object, eventData: Object?): Map
Parameters
options
(Object)
Options describing the destination and animation of the
transition.
Accepts
CameraOptions
,
AnimationOptions
,
and the following additional options.
Name | Type | Description |
---|---|---|
options.curve |
number
(default: 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.minZoom |
number?
|
The zero-based zoom level at the peak of the flight
path. If
options.curve
is specified, this option is ignored.
|
options.speed |
number
(default: 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.screenSpeed |
number?
|
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.maxDuration |
number?
|
The animation's maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0. |
eventData
(Object?)
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;
}
});
Events
Fired immediately after the map has been resized.
resize
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired immediately after the map has been removed with Map.event:remove.
remove
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
weatheralert.eventname
Fired when layer is removed.
content.remove
Type: Object
Properties
object
(ContentRemoveEvent)
: with layer id has been returned.
content.remove
Fired when layer visibility changes.
content.visibility
Type: Object
Properties
object
(ContentVisibilityEvent)
: with layer id has been returned.
content.visibility
content.filter
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.
mousedown
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener
map.on('mousedown', function() {
console.log('A mousedown event has occurred.');
});
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
mouseup
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener
map.on('mouseup', function() {
console.log('A mouseup event has occurred.');
});
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
mouseover
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener
map.on('mouseover', function() {
console.log('A mouseover event has occurred.');
});
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
mousemove
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener
map.on('mousemove', function() {
console.log('A mousemove event has occurred.');
});
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
click
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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 TrimbleMaps.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);
});
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
specified layer.
dblclick
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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 TrimbleMaps.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);
});
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.
mouseenter
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
mouseleave
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a point device (usually a mouse) leaves the map's canvas.
mouseout
Properties
data
(MapMouseEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a wheel
event occurs within the map.
wheel
Properties
data
(MapWheelEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a touchstart
event occurs within the map.
touchstart
Properties
data
(MapTouchEvent)
: // Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a touchend
event occurs within the map.
touchend
Properties
data
(MapTouchEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a touchmove
event occurs within the map.
touchmove
Properties
data
(MapTouchEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a touchcancel
event occurs within the map.
touchcancel
Properties
data
(MapTouchEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
movestart
Properties
data
({originalEvent: DragEvent})
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired repeatedly during an animated transition from one view to another, as the result of either user interaction or methods such as Map#flyTo.
move
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener that fires
// repeatedly during an animated transition.
map.on('move', function() {
console.log('A move event occurred.');
});
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.
moveend
Properties
data
({originalEvent: DragEvent})
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "drag to pan" interaction starts. See DragPanHandler.
dragstart
Properties
data
({originalEvent: DragEvent})
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired repeatedly during a "drag to pan" interaction. See DragPanHandler.
drag
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "drag to pan" interaction ends. See DragPanHandler.
dragend
Properties
data
({originalEvent: DragEvent})
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
zoomstart
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
zoom
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener that fires
// repeatedly during a zoom transition.
map.on('zoom', function() {
console.log('A zoom event occurred.');
});
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.
zoomend
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "drag to rotate" interaction starts. See DragRotateHandler.
rotatestart
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired repeatedly during a "drag to rotate" interaction. See DragRotateHandler.
rotate
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "drag to rotate" interaction ends. See DragRotateHandler.
rotateend
Properties
data
((MapMouseEvent | MapTouchEvent))
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as Map#flyTo .
pitchstart
Properties
data
(MapEventData)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
pitch
Properties
data
(MapEventData)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired immediately after the map's pitch (tilt) finishes changing as the result of either user interaction or methods such as Map#flyTo.
pitchend
Properties
data
(MapEventData)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "box zoom" interaction starts. See BoxZoomHandler.
boxzoomstart
Properties
data
(MapBoxZoomEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when a "box zoom" interaction ends. See BoxZoomHandler.
boxzoomend
Type: Object
Properties
data
(MapBoxZoomEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. See BoxZoomHandler.
boxzoomcancel
Properties
data
(MapBoxZoomEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when the WebGL context is lost.
webglcontextlost
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when the WebGL context is restored.
webglcontextrestored
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred.
load
Type: Object
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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
render
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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
idle
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
error
Properties
data
({error: {message: string}})
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
// Set an event listener that fires
// when an error occurs.
map.on('error', function() {
console.log('A error event occurred.');
});
Fired when any map data loads or changes. See MapDataEvent for more information.
data
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when the map's style loads or changes. See MapDataEvent for more information.
styledata
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
sourcedata
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when any map data (style, source, tile, etc) begins loading or
changing asyncronously. All dataloading
events are followed
by a data
or error
event. See MapDataEvent
for more information.
dataloading
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
styledataloading
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when one of the map's sources begins loading or changing
asyncronously.
All sourcedataloading
events are followed by a
sourcedata
or error
event.
See MapDataEvent for more information.
sourcedataloading
Properties
data
(MapDataEvent)
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
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.
styleimagemissing
Properties
id
(string)
: The id of the missing image.
Example
// Initialize the map
var map = new TrimbleMaps.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.');
});
Fired when the map style is changing.
stylechanging
Properties
previousStyleName
(string)
: The name of the current map style.
styleName
(string)
: The name of the new map style being loaded.
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
map.on('stylechanging', function(evt) {
console.log(`Changing from style ${evt.previousStyleName} to ${evt.styleName}`);
});
Fired when the map style has changed.
stylechange
Properties
styleName
(string)
: The name of the new map style being loaded.
Example
// Initialize the map
var map = new TrimbleMaps.Map({ // map options });
map.on('stylechange', function(evt) {
console.log(`The map style has changed to ${evt.styleName}`);
});
customroadloading
customroad
trafficcameraloading
trafficcamera
trafficincidentloading
trafficincident
truckrestrictionloading
truckrestriction
weatherradarloading
weatherradar
weathercloudloading
weathercloud
weatheralertloading
weatheralert
trafficloading
traffic
roadsurfaceloading
roadsurface
pointsofinterestloading
pointsofinterest
AnimationOptions
Options common to map movement methods that involve animation, such as Map#panBy and Map#easeTo, controlling the duration and easing function of the animation. All properties are optional.
AnimationOptions
Type: Object
Properties
duration
(number)
: The animation's duration, measured in milliseconds.
easing
(Function)
: A function taking a time in the range 0..1 and returning a number where 0 is
the initial state and 1 is the final state.
offset
(PointLike)
: of the target center relative to real map container center at the end of
animation.
essential
(boolean)
: If
true
, then the animation is considered essential and will not be affected by
prefers-reduced-motion
.
CameraOptions
Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the desired location, zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current camera value for that property will remain unchanged.
CameraOptions
Type: Object
Properties
center
(LngLatLike)
: The desired center.
zoom
(number)
: The desired zoom level.
bearing
(number)
: The desired bearing in degrees. The bearing is the compass direction that
is "up". For example,
bearing: 90
orients the map so that east is up.
pitch
(number)
: The desired pitch in degrees. The pitch is the angle towards the horizon
measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0
provides the appearance
of looking straight down at the map, while pitch: 60 tilts the user's perspective
towards the horizon.
Increasing the pitch value is often used to display 3D objects.
around
(LngLatLike)
: If
zoom
is specified,
around
determines the point around which the zoom is centered.
padding
(PaddingOptions)
: Dimensions in pixels applied on each side of the viewport for shifting the
vanishing point.
Example
// set the map's initial perspective with CameraOptions
var map = new TrimbleMaps.Map({
container: 'map',
style: TrimbleMaps.Common.Style.TRANSPORTATION,
center: [-73.5804, 45.53483],
pitch: 60,
bearing: -60,
zoom: 10
});
PaddingOptions
Options for setting padding on calls to methods such as Map#fitBounds, Map#fitScreenCoordinates, and Map#setPadding. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be non-negative integers.
PaddingOptions
Type: Object
Properties
top
(number)
: Padding in pixels from the top of the map canvas.
bottom
(number)
: Padding in pixels from the bottom of the map canvas.
left
(number)
: Padding in pixels from the left of the map canvas.
right
(number)
: Padding in pixels from the right of the map canvas.
Example
var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: 20
});
RequestParameters
A RequestParameters
object to be returned from Map.options.transformRequest
callbacks.
RequestParameters
Type: Object
Properties
url
(string)
: The URL to be requested.
headers
(Object)
: The headers to be sent with the request.
body
(string)
: Request body.
credentials
(string)
: 'same-origin'|'include'
Use 'include' to send cookies with cross-origin requests.
collectResourceTiming
(boolean)
: If true, Resource Timing API information will be collected for these transformed
requests and returned in a resourceTiming property of relevant data events.
Example
// use transformRequest to modify requests that begin with `http://myHost`
transformRequest: function(url, resourceType) {
if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
return {
url: url.replace('http', 'https'),
headers: { 'my-custom-header': true },
credentials: 'include' // Include cookies for cross-origin requests
}
}
}
CustomLayerInterface
Interface for custom style layers. This is a specification for implementers to model: it is not an exported method or class.
Custom layers allow a user to render directly into the map's GL context using the map's camera. These layers can be added between any regular layers using Map#addLayer.
Custom layers must have a unique id
and must have the type
of
"custom"
.
They must implement render
and may implement prerender
,
onAdd
and onRemove
.
They can trigger rendering using Map#triggerRepaint
and they should appropriately handle Map.event:webglcontextlost and
Map.event:webglcontextrestored.
The renderingMode
property controls whether the layer is treated as a
"2d"
or "3d"
map layer. Use:
"renderingMode": "3d"
to use the depth buffer and share it with other layers"renderingMode": "2d"
to add a layer with no depth. If you need to use the depth buffer for a"2d"
layer you must use an offscreen framebuffer and CustomLayerInterface#prerender
CustomLayerInterface
Properties
id
(string)
: A unique layer id.
Example
// Custom layer implemented as ES6 class
class NullIslandLayer {
constructor() {
this.id = 'null-island';
this.type = 'custom';
this.renderingMode = '2d';
}
onAdd(map, gl) {
const vertexSource = `
uniform mat4 u_matrix;
void main() {
gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);
gl_PointSize = 20.0;
}`;
const fragmentSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentSource);
gl.compileShader(fragmentShader);
this.program = gl.createProgram();
gl.attachShader(this.program, vertexShader);
gl.attachShader(this.program, fragmentShader);
gl.linkProgram(this.program);
}
render(gl, matrix) {
gl.useProgram(this.program);
gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix);
gl.drawArrays(gl.POINTS, 0, 1);
}
}
map.on('load', function() {
map.addLayer(new NullIslandLayer());
});
Instance Members
Optional method called when the layer has been added to the Map with Map#addLayer. This gives the layer a chance to initialize gl resources and register event listeners.
onAdd(map: Map, gl: WebGLRenderingContext)
Parameters
map
(Map)
The Map this custom layer was just added to.
gl
(WebGLRenderingContext)
The gl context for the map.
Optional method called when the layer has been removed from the Map with Map#removeLayer. This gives the layer a chance to clean up gl resources and event listeners.
onRemove(map: Map, gl: WebGLRenderingContext)
Parameters
map
(Map)
The Map this custom layer was just added to.
gl
(WebGLRenderingContext)
The gl context for the map.
Optional method called during a render frame to allow a layer to prepare resources or render into a texture.
The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.
prerender(gl: WebGLRenderingContext, matrix: Array<number>)
Parameters
gl
(WebGLRenderingContext)
The map's gl context.
matrix
(Array<number>)
The map's camera matrix. It projects spherical mercator
coordinates to gl coordinates. The mercator coordinate
[0, 0]
represents the
top left corner of the mercator world and
[1, 1]
represents the bottom right corner. When
the
renderingMode
is
"3d"
, the z coordinate is conformal. A box with identical x, y, and
z
lengths in mercator units would be rendered as a cube.
MercatorCoordinate
.fromLngLat
can be used to project a
LngLat
to a mercator coordinate.
Called during a render frame allowing the layer to draw into the GL context.
The layer can assume blending and depth state is set to allow the layer to properly blend and clip other layers. The layer cannot make any other assumptions about the current GL state.
If the layer needs to render to a texture, it should implement the
prerender
method
to do this and only use the render
method for drawing
directly into the main framebuffer.
The blend function is set to
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
. This expects
colors to be provided in premultiplied alpha form where the
r
, g
and b
values are already
multiplied by the a
value. If you are unable to provide
colors in premultiplied form you
may want to change the blend function to
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
.
render(gl: WebGLRenderingContext, matrix: Array<number>)
Parameters
gl
(WebGLRenderingContext)
The map's gl context.
matrix
(Array<number>)
The map's camera matrix. It projects spherical mercator
coordinates to gl coordinates. The spherical mercator coordinate
[0, 0]
represents the
top left corner of the mercator world and
[1, 1]
represents the bottom right corner. When
the
renderingMode
is
"3d"
, the z coordinate is conformal. A box with identical x, y, and
z
lengths in mercator units would be rendered as a cube.
MercatorCoordinate
.fromLngLat
can be used to project a
LngLat
to a mercator coordinate.
supported
Test whether the browser supports the JavaScript Maps SDK.
supported(options: Object?): boolean
Parameters
Returns
boolean
:
Example
TrimbleMaps.supported() // = true
version
The version of the JavaScript Maps SDK in use as specified in package.json
.
version
Type: string
Enumerations for common property values.
Enumerations
Common
Common enumerations used across TrimbleMaps.
Common
Static Members
Enumeration for map style values.
Style
Parameters
TRANSPORTATION
(string)
SATELLITE
(string)
TERRAIN
(string)
BASIC
(string)
BASIC_DARK
(string)
DATALIGHT
(string)
DATADARK
(string)
TRANSPORTATION_DARK
(string)
ACCESSIBLE_LIGHT
(string)
ACCESSIBLE_DARK
(string)
MOBILE_DAY
(string)
MOBILE_NIGHT
(string)
MOBILE_SATELLITE
(string)
SIMPLE_LIGHT
(string)
SIMPLE_DARK
(string)
Example
var map = new TrimbleMaps.Map({
container: 'map',
center: [-122.420679, 37.772537],
zoom: 13,
style: TrimbleMaps.Common.Style.TRANSPORTATION
});
Enumeration for the routing HazMat type.
HazMatType
Properties
Represents vehicle dimensions of a truck trailer to use for.
TruckConfig
Properties
NONE
(number)
: Indicates that no particular truck style is chosen
TWENTY_EIGHT
(number)
: Indicates that a 28' double trailer should be used
FORTY
(number)
: Indicates that a Heavy Duty Straight trailer should be used
FORTY_EIGHT
(number)
: Indicates that a Heavy Duty Semitrailer (48' x 96") should be used
FIFTY_THREE
(number)
: Indicates that a Heavy Duty Semitrailer should be used
FULL_SIZE_VAN
(number)
: Indicates a full-size van
TWENTY_SIX
(number)
: Indicates a Medium Duty Straight trailer
CONVENTIONAL_SCHOOL_BUS
(number)
: Indicates a conventional school bus
SMALL_SCHOOL_BUS
(number)
: Indicates a small school bus
Enumeration for the routing currency units.
TollCurrency
Properties
USD
(number)
: US dollars
CAD
(number)
: Canadian dollars
ALL
(number)
: Albanian lek
AMD
(number)
: Aremenian dram
AZN
(number)
: Azerbaijani manat
BAM
(number)
: Bosnia and Herzegovina convertible mark
BGN
(number)
: Bulgarian lev
BYR
(number)
: Belarusian ruble
CHF
(number)
: Swiss franc
CZK
(number)
: Czech koruna
DKK
(number)
: Danish krone
EUR
(number)
: Euros
GBP
(number)
: Pound sterling
GEL
(number)
: Georgian lari
HRK
(number)
: Croatian kuna
HUF
(number)
: Hungarian forint
ISK
(number)
: Icelandic króna: second króna
MDL
(number)
: Moldovan leu
MKD
(number)
: Second Macedonian denar
NOK
(number)
: Norwegian krone
PLN
(number)
: Polish złoty
RON
(number)
: Fourth Romanian leu
RSD
(number)
: Serbian dinar
RUB
(number)
: Russian ruble
SEK
(number)
: Swedish krona
TRY
(number)
: Turkish lira
UAH
(number)
: Ukrainian hryvnia
Time zone option
TimeZone
Properties
LOCAL
(number)
: Local
SYSTEM
(number)
: System
HAWAII
(number)
: Hawaii
ALASKA
(number)
: Alaska
PACIFIC
(number)
: Pacific
ARIZONA
(number)
: Arizona
MOUNTAIN
(number)
: Mountain
CENTRAL
(number)
: Central
EASTERN
(number)
: Eastern
ATLANTIC
(number)
: Atlantic
NEWFOUNDLAND
(number)
: Newfoundland
GMT
(number)
: GMT Greenwich Mean Time
UTC
(number)
: Coordinated Universal Time
Represents the EU Tunnel categories. Applicable for EU region only.
TunnelCategory
Properties
Fuel type
FuelType
Properties
Side of street adherence level
SideOfStreetAdherenceLevel
Properties
OFF
(number)
: Will not reroute according to the side of the street.
MINIMAL
(number)
: Adds a cost of a quarter of a mile to ending up on the wrong side
of the street.
MODERATE
(number)
: Adds a cost of half a mile to ending up on the wrong side of the
street.
AVERAGE
(number)
: Adds a cost of one mile to ending up on the wrong side of the
street.
STRICT
(number)
: Adds a cost of five miles to ending up on the wrong side of the
street.
ADHERE
(number)
: Adds a cost of 10 miles to ending up on the wrong side of the
street.
STRONGLY_ADHERE
(number)
: Adds a cost of 1,000 miles to ending up on the wrong side of the
street.
Represents which Hours Of Service rule to use
HoSScheduleType
Properties
US_FED_607_LH
(number)
: Use US Federal Long Haul 60/7 rule
US_FED_708_LH
(number)
: Use US Federal Long Haul 70/8 rule
CANADA_CYCLE_1
(number)
: Use Canada Cycle 1 rule
CANADA_CYCLE_2
(number)
: Use Canada Cycle 2 rule
CALIFORNIA_808
(number)
: Use California Intrastate rule
TEXAS_707
(number)
: Use Texas Intrastate rule
US_SHORT_HAUL
(number)
: Use Short Haul Exemption
EUROPE
(number)
: Use European 48 hour rule
UNKNOWN
(number)
: Unknown or uninitialized schedule type
Represents the type of roads for road speeds.
RoadType
Properties
INTER_STATE_RURAL
(number)
: Indicates a rural interstate road type.
DIVIDED_RURAL
(number)
: Indicates rural divided road type.
PRIMARY_RURAL
(number)
: Indicates a rural primary road type.
FERRIES_RURAL
(number)
: Indicates a rural ferry road type.
SECONDARY_RURAL
(number)
: Indicates a rural secondary road type.
RAMP_RURAL
(number)
: Indicates a rural ramp road type.
LOCAL_RURAL
(number)
: Indicates a rural local road type.
INTER_STATE_URBAN
(number)
: Indicates an urban interstate road type.
DIVIDED_URBAN
(number)
: Indicates an urban divided road type.
DIVIDED_URBAN
(number)
: Indicates an urban primary road type.
FERRIES_URBAN
(number)
: Indicates an urban ferry road type.
SECONDARY_URBAN
(number)
: Indicates an urban secondary road type.
RAMP_URBAN
(number)
: Indicates an urban ramp road type.
LOCAL_URBAN
(number)
: Indicates an urban local road type.
Format for rail freight stations.
RailStationFormat
Properties
STATION_STATE
(string)
: There are three parts that make up the StationState. Station name,
space, and State abbreviation. StationState is not case sensitive.
Examples for Oakland, California: Oakland CA
SPLC
(string)
: Standard Point Location Code. 9 digit geographic code used by
North American transportation industries. PC*Miler|Rail will only
use the first 6 digits. Example for Boston, Massachusetts: 142000
ERPC
(string)
: Eastern Railroad President's Conference Codes also referred to as
3-3-3. There are three parts that make up the ERPC. Station name,
space, and State abbreviation. ERPC is not case sensitive. Examples
for Cabazon, California: Cabazon CA
FSAC
(string)
: Freight Station Accounting Code. FSAC is a 5 digit code with
leading zeros. Examples: 11121
R260
(string)
: Rule 260 Junction Code. R260 is 5 characters long and is not case
sensitive. Examples: PACIF
Route calculation heuristic.
RailRoutePreference
Properties
PRACTICAL
(string)
: Practical routing is the optimal for general merchandise traffic.
INTERMODAL
(string)
: Intermodal routing is specific to intermodal trains. Only
locations with intermodal service can be entered as
origin/destinations.
SHORTEST
(string)
: Shortest routing will route to the shortest path.
COAL_BULK
(string)
: Coal/Bulk Routing is specific to Coal/Bulk unit trains.
AUTO_RACKS
(string)
: AutoRack routing is specific to multi-levels.
FUEL_SURCHARGE
(string)
: Fuel Surcharge routing is practical or shortest routing depending
on the railroad.
Enumeration for the Satellite Provider.
SatelliteProvider
Properties
DEFAULT
(string)
: satellite source provider for default DigitalGlobeAPIImagery
SAT1
(string)
: DigitalGlobe
SAT2
(string)
: DigitalGlobeConsumer
SAT3
(string)
: DigitalGlobeTrueCurrency
SAT4
(string)
: DigitalGlobeColorConsumer
SAT5
(string)
: DigitalGlobeAPIVivid
SAT6
(string)
: DigitalGlobeAPIRecent
ALKCURATED
(string)
: DigitalGlobeAPIImagery certain curated data is excluded.
Geography & Geometry
LngLat
and LngLatBounds
represent points and rectangles in
geographic
coordinates. Point
represents points in screen coordinates.
LngLat
A LngLat
object represents a given longitude and latitude coordinate,
measured in degrees.
The JavaScript Maps SDK uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.
Note that any JavaScript Maps SDK method that accepts a LngLat
object as an
argument or option
can also accept an Array
of two numbers and will perform an implicit
conversion.
This flexible type is documented as LngLatLike.
new LngLat(lng: number, lat: number)
Parameters
Example
var ll = new TrimbleMaps.LngLat(-73.9749, 40.7736);
Static Members
Converts an array of two numbers or an object with lng
and
lat
or lon
and lat
properties
to a LngLat
object.
If a LngLat
object is passed in, the function returns it
unchanged.
convert(input: LngLatLike): LngLat
Parameters
Returns
LngLat
:
A new
LngLat
object, if a conversion occurred, or the original
LngLat
object.
Example
var arr = [-73.9749, 40.7736];
var ll = TrimbleMaps.LngLat.convert(arr);
ll; // = LngLat {lng: -73.9749, lat: 40.7736}
Instance Members
Returns the approximate distance between a pair of coordinates in meters Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159)
distanceTo(lngLat: LngLat): number
Parameters
lngLat
(LngLat)
coordinates to compute the distance to
Returns
number
:
Distance in meters between the two coordinates.
Example
var new_york = new TrimbleMaps.LngLat(-74.0060, 40.7128);
var los_angeles = new TrimbleMaps.LngLat(-118.2437, 34.0522);
new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km
Returns a LngLatBounds
from the coordinates extended by a
given radius
. The returned LngLatBounds
completely contains the radius
.
toBounds(radius: number): LngLatBounds
Parameters
radius
(number
= 0
)
Distance in meters from the coordinates to extend the bounds.
Returns
LngLatBounds
:
A new
LngLatBounds
object representing the coordinates extended by the
radius
.
Example
var ll = new TrimbleMaps.LngLat(-73.9749, 40.7736);
ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]
LngLatLike
A LngLat object, an array of two numbers representing longitude and
latitude,
or an object with lng
and lat
or lon
and
lat
properties.
LngLatLike
Type: (LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number])
Example
var v1 = new TrimbleMaps.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];
var v3 = {lon: -122.420679, lat: 37.772537};
LngLatBounds
A LngLatBounds
object represents a geographical bounding box,
defined by its southwest and northeast points in longitude and latitude.
If no arguments are provided to the constructor, a null
bounding box is
created.
Note that any the JavaScript Maps SDK method that accepts a LngLatBounds
object as an argument or option
can also accept an Array
of two LngLatLike
constructs and will perform an implicit conversion.
This flexible type is documented as LngLatBoundsLike.
new LngLatBounds(sw: LngLatLike?, ne: LngLatLike?)
Parameters
sw
(LngLatLike?)
The southwest corner of the bounding box.
ne
(LngLatLike?)
The northeast corner of the bounding box.
Example
var sw = new TrimbleMaps.LngLat(-73.9876, 40.7661);
var ne = new TrimbleMaps.LngLat(-73.9397, 40.8002);
var llb = new TrimbleMaps.LngLatBounds(sw, ne);
Static Members
Converts an array to a LngLatBounds
object.
If a LngLatBounds
object is passed in, the function returns
it unchanged.
Internally, the function calls LngLat#convert
to convert
arrays to LngLat
values.
convert(input: LngLatBoundsLike): LngLatBounds
Parameters
input
(LngLatBoundsLike)
An array of two coordinates to convert, or a
LngLatBounds
object to return.
Returns
LngLatBounds
:
A new
LngLatBounds
object, if a conversion occurred, or the original
LngLatBounds
object.
Example
var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
var llb = TrimbleMaps.LngLatBounds.convert(arr);
llb; // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}
Instance Members
Set the northeast corner of the bounding box
setNorthEast(ne: LngLatLike): LngLatBounds
Parameters
ne
(LngLatLike)
northeast
Returns
LngLatBounds
:
this
Set the southwest corner of the bounding box
setSouthWest(sw: LngLatLike): LngLatBounds
Parameters
sw
(LngLatLike)
southwest
Returns
LngLatBounds
:
this
Extend the bounds to include a given LngLat or LngLatBounds.
extend(obj: (LngLat | LngLatBounds)): LngLatBounds
Parameters
obj
((LngLat | LngLatBounds))
object to extend to
Returns
LngLatBounds
:
this
Returns the bounding box represented as an array.
toArray(): Array<Array<number>>
Returns
Array<Array<number>>
:
The bounding box represented as an array, consisting of the
southwest and northeast coordinates of the bounding represented as arrays of
numbers.
Example
var llb = new TrimbleMaps.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]
Return the bounding box represented as a string.
toString(): string
Returns
string
:
The bounding box represents as a string of the format
'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'
.
Example
var llb = new TrimbleMaps.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))"
Check if the point is within the bounding box.
contains(lnglat: LngLatLike): boolean
Parameters
lnglat
(LngLatLike)
geographic point to check against.
Returns
boolean
:
True if the point is within the bounding box.
Example
var llb = new TrimbleMaps.LngLatBounds(
new TrimbleMaps.LngLat(-73.9876, 40.7661),
new TrimbleMaps.LngLat(-73.9397, 40.8002)
);
var ll = new TrimbleMaps.LngLat(-73.9567, 40.7789);
console.log(llb.contains(ll)); // = true
LngLatBoundsLike
A LngLatBounds object, an array of LngLatLike objects in [sw, ne] order, or an array of numbers in [west, south, east, north] order.
LngLatBoundsLike
Type: (LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number])
Example
var v1 = new TrimbleMaps.LngLatBounds(
new TrimbleMaps.LngLat(-73.9876, 40.7661),
new TrimbleMaps.LngLat(-73.9397, 40.8002)
);
var v2 = new TrimbleMaps.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])
var v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
Point
A Point
geometry object, which has
x
and y
properties representing screen coordinates in pixels.
Point
Type: Object
Example
var point = new TrimbleMaps.Point(-77, 38);
PointLike
A Point or an array of two numbers representing x
and
y
screen coordinates in pixels.
PointLike
Example
var p1 = new TrimbleMaps.Point(-77, 38); // a PointLike which is a Point
var p2 = [-77, 38]; // a PointLike which is an array of two numbers
Route visualization.
Route Layer
Route
Creates a route component
new Route(options: RouteOptions)
Extends Evented
Parameters
options
(RouteOptions)
Name | Type | Description |
---|---|---|
options.routeId |
string?
|
A unique string values used to identify a route. It is needed when removing or updating a route. |
options.routeColor |
string?
|
The color of the route line |
options.routePathOpacity |
number?
|
The opacity of the route line |
options.routeWidth |
(RouteWidth | number)?
|
The width of the route line. Example 20 or {stops: [ [10, 7] , [15, 9] , [19, 11] ]} |
options.stops |
Array<(LngLatLike | StopOptions)>?
|
An array of at least two
TrimbleMaps.LngLat
or
StopOptions
objects containing the locations of the stops of the route. When
StopOptions are used, the
requestMethod
parameter will be ignored and the type will be POST.
|
options.vehicleType |
Common.VehicleType?
|
Default:
TrimbleMaps.Common.VehicleType.TRUCK
Restricts the route to roads that are accessible by the selected vehicle type.
|
options.routeType |
Common.RouteType?
|
Default:
TrimbleMaps.Common.RouteType.PRACTICAL
Type of route.
|
options.routeOptimization |
Common.RouteOptimization?
|
Default:
TrimbleMaps.Common.RouteOptimization.NONE
|
options.tollDiscourage |
boolean?
|
Default:
false
Generates the route by trying to avoid toll roads. Deprecated. |
options.tollRoads |
Common.TollRoadsType?
|
Defaut is null. If it is null, tollDiscourage will be used. |
options.afSetIDs |
Array<number>?
|
The IDs of the Route Modifier (avoid/favor) sets that should be applied to the route. The format is comma separated IDs. The IDs are integers. Set to [-1] to select all sets. |
options.afSetNames |
Array<string>?
|
The names of the Route Modifier (avoid/favor) sets that should be applied to the route. Default is an empty set. |
options.bordersOpen |
boolean?
|
Default:
true
Indicates whether borders are open for travel. |
options.overrideRestrict |
boolean?
|
Default:
false
Indicates whether or not to override truck restrictions. |
options.highwayOnly |
boolean?
|
Default:
false
Restricts the route to only highway roads. |
options.hazMatType |
Common.HazMatType?
|
Default:
TrimbleMaps.Common.HazMatType.NONE
Restricts the route to roads that allow transportation of the selected hazardous material.
Deprecated. Use hazMatTypes instead. |
options.hazMatTypes |
Array<Common.HazMatType>?
|
Indicates the hazardous material types. |
options.tunnelCategories |
Array<Common.TunnelCategory>?
|
Represents the EU Tunnel categories. |
options.customRoadSpeeds |
Array<RoadSpeedBase>?
|
A list of custom road speeds to be applied for the route. |
options.distanceUnits |
Common.DistanceUnit?
|
Default:
TrimbleMaps.Common.DistanceUnit.MILES
Distance units as miles or kilometers.
|
options.trkLCV |
boolean?
|
Indicates whether the truck is a multi-trailer or longer combination vehicle. |
options.trkUnits |
Common.TruckUnit?
|
Default:
TrimbleMaps.Common.TruckUnit.ENGLISH
Sets truck dimensions as English or Metric.
|
options.trkHeight |
number?
|
The height of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
options.trkLength |
number?
|
The length of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
options.trkWidth |
number?
|
The width of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
options.trkWeight |
number?
|
The weight of the vehicle in pounds or kilograms depending on units. |
options.trkAxles |
number?
|
Default: 5
The number of axles on the vehicle; acceptable values are 2 through 14. |
options.trkMaxWeightPerAxleGroup |
number?
|
Weight per axle |
options.trkTireCount |
number?
|
Tire count |
options.ferryDiscourage |
boolean?
|
Default:
false
Indicates whether or not to discourage the use of ferries when creating the route. |
options.inclFerryDist |
boolean?
|
Default:
true
Indicates whether or not to include ferry distances in mileage calculations of reports. |
options.fuelUnits |
Common.FuelUnit?
|
Default:
TrimbleMaps.Common.FuelUnit.GALLONS
Fuel units as gallons and liters.
|
options.truckConfig |
Common.TruckConfig?
|
Default:
TrimbleMaps.Common.TruckConfig.NONE
The vehicle style.
|
options.inclTollData |
boolean?
|
Default:
true
Indicates whether or not reports should calculate toll costs in reports. |
options.fuelEconLoad |
number?
|
The fuel efficiency (distance units per fuel units) when loaded. Used for reports. |
options.fuelEconEmpty |
number?
|
The fuel efficiency (distance units per fuel units) when empty. Used for reports. |
options.costPerFuelUnit |
number?
|
The cost per fuel unit of fuel. Used for reports. |
options.costGHG |
number?
|
The cost of greenhouse gas in lbs. per fuel unit. Used for reports |
options.costMaintLoad |
number?
|
The maintenance cost per distance unit when loaded. Used for reports. |
options.costMaintEmpty |
number?
|
The maintenance cost per distance unit when empty. Used for reports. |
options.costTimeLoad |
number?
|
The time cost per mile/km when loaded. Used for reports. |
options.costTimeEmpty |
number?
|
The time cost per mile/km when empty. Used for reports. |
options.tollCurrency |
Common.TollCurrency?
|
Default:
TrimbleMaps.Common.TollCurrency.USD
|
options.exchangeRate |
number?
|
The change rate to convert US dollars to Canadian dollars. Used for reports. |
options.tollPlan |
string?
|
Toll discount program. This field is only valid if the user has quarterly toll data privileges and the inclTollData (UseTollData) is set to true. |
options.custRdSpeeds |
boolean?
|
Indicating whether or not to use custom road speeds. |
options.useEUTollsReport |
boolean?
|
Indicating whether EU toll report should be reported. |
options.useNonNaTolls |
boolean?
|
Indicating whether SA toll report should be reported. |
options.includeRoadClass |
boolean?
|
Indicating whether the RoadClass will be included in the report. |
options.citeInt |
number?
|
The cite interval to be used when generating a geotunnel report. The minimum value is 0.1. Used for reports. |
options.region |
Common.Region?
|
Default:
TrimbleMaps.Common.Region.NA
The data region in which the route stops are located.
|
options.dataVersion |
Common.DataVersion?
|
|
options.reportType |
Array?
|
Default:
[TrimbleMaps.Common.ReportType.MILEAGE]
The data region in which the route stops are located.
|
options.elevLimit |
number?
|
Elevation limit when generating a route |
options.hosEnabled |
boolean?
|
Gets or sets whether HoursOfService is enabled. |
options.hosRemDriveTimeUntilBreak |
number?
|
Gets or sets the available driving hours at origin before the driver needs to take a rest break. The format is in seconds. |
options.hosRemDriveTime |
number?
|
Gets or sets the available driving hours at origin until the end of work day. The format is in seconds. |
options.hosRemOnDutyTime |
number?
|
Gets or sets the available On-Duty hours available at origin until the end of work day. The format is in seconds. |
options.hosRuleType |
Common.HoSScheduleType?
|
Gets or sets the hours of service rule currently in use. |
options.hosRemCycleDutyTime |
number?
|
Gets or sets the available Cycle duty time at origin until Cycle reset. The format is in seconds. |
options.hosCycleTimeGains |
Array<number>?
|
The list of cycle time gains per day. The format is in seconds. |
options.hosLastCycleResetDateTime |
string?
|
The last cycle reset for Canadian hours of service |
options.hosLast24HourBreakDateTime |
string?
|
The date and time of the last off duty break that was at least 24 consecutive hours for Canadian hours of service. |
options.hosRemainingCanadaOnDutyTime |
number?
|
The available On-Duty hours available at origin until the end of work day. The format is in seconds. |
options.hosRemainingDriveTimeUntilBreakDriver2 |
number?
|
The available driving hours at origin before the driver needs to take a rest break. The format is in seconds. Used only in Team Driving. |
options.hosRemainingDriveTimeDriver2 |
number?
|
The available driving hours at origin until the end of work day. The format is in seconds. Used only in Team Driving. |
options.hosRemainingOnDutyTimeDriver2 |
number?
|
The available On-Duty hours available at origin until the end of work day. The format is in seconds. Used only in Team Driving. |
options.hosRemainingCycleDutyTimeDriver2 |
number?
|
The available Cycle duty time at origin until Cycle reset. The format is in seconds. Used only in Team Driving. |
options.hosCycleTimeGainsDriver2 |
Array<number>?
|
The list of cycle time gains per day. The format is in seconds. Used only in Team Driving. |
options.hosLastCycleResetDateTimeDriver2 |
string?
|
The time of the last cycle reset for Canadian hours of service. Used only in Team Driving. |
options.hosLast24HourBreakDateTimeDriver2 |
string?
|
The date and time of the last off duty break that was at least 24 consecutive hours for Canadian hours of service. Used only in Team Driving. |
options.hosRemainingCanadaOnDutyTimeDriver2 |
number?
|
The available On-Duty hours available at origin until the end of work day. The format is in seconds. Used only in Team Driving. |
options.hosAlternateHoSRuleType |
number?
|
The alternate Hours of Service rule type to use if crossing international borders between the US and Canada. |
options.hosRemainingTimeUntilFullDayBreak |
number?
|
The available On-Duty hours available at origin until the driver must take a 24 hour break. |
options.hosRemainingTimeUntilFullDayBreakDriver2 |
number?
|
The available On-Duty hours available for Driver 2 at origin until the driver must take a 24 hour break. Used for Canada Cycle Two only. The format is in seconds. |
options.hosRemainingDrivingTimeInWeek |
number?
|
The available Driving hours available at origin until the driver must a break. Used for Europe only. The format is in seconds. |
options.hosRemainingOnDutyTimeInDay |
number?
|
The available On Duty Time In Day hours available at origin until the driver must a break. Used for Europe only. The format is in seconds. |
options.hosRemainingConsecutiveDrivingTime |
number?
|
The available Consecutive Driving hours available at origin until the driver must a break. Used for Europe only. The format is in seconds. |
options.hosRemainingFortnightlyTime |
number?
|
The available Fortnightly hours available at origin until the driver must a break. Used for Europe only. The format is in seconds. |
options.hosCurrentOffDutyTime |
number?
|
The rest time already taken at a stop. Used for NA and Europe, regular and team driving. The format is in seconds. |
options.hosCurrentOffDutyTimeDriver2 |
number?
|
The rest time already taken at a stop. Used for NA and Europe, regular and team driving. The format is in seconds. |
options.hosUseCycleReset |
boolean?
|
Whether we do full cycle time reset or not. |
options.hosTerminalDayStartTime |
string?
|
The time of day used to determine when a 24-hour period defining a 'day' starts. The format should be "HH:mm:sszzz" |
options.hosUseCustomPlaces |
boolean?
|
Whether to use custom places for HOS rest stops. |
options.hosTeamDriving |
boolean?
|
Whether there are team drivers. |
options.hosShortBreakDuration |
number?
|
The short break duration. The format is in seconds. CustomBreakDurations |
options.hosEndOfDutyBreakDuration |
number?
|
The end of duty break duration. The format is in seconds. CustomBreakDurations |
options.hosCycleResetBreakDuration |
number?
|
The cycle reset break duration. The format is in seconds. CustomBreakDurations |
options.hosDriverSwitchBreakDuration |
number?
|
The driver switch break duration. The format is in seconds. CustomBreakDurations |
options.hosBorderCrossingWaitDuration |
number?
|
The time spent waiting at border crossings. The format is in seconds. CustomBreakDurations |
options.hosBreakTimeInDayDuration |
number?
|
The break time in day duration. The format is in seconds. Used for HOS Europe only. CustomBreakDurations |
options.hosBreakTimeInWeekDuration |
number?
|
The break time in week duration. The format is in seconds. Used for HOS Europe only. CustomBreakDurations |
options.hosMaxAlternateRestStops |
number?
|
Whether the maximum number of Alternate Rest Stops to be displayed in the report. Defaults to 0. |
options.hosSkipRestStopInsertion |
boolean?
|
Whether to skip inserting rest stops in the route |
options.hosActiveDriver |
number?
|
Whether the active driver at the beginning of the trip. Used for Team Driving. |
options.hosMaxDrivingTimeInDay |
number?
|
The maximum driving time allowed in a day. Used for HOS Europe only |
options.hosMaxOnDutyTimeInDay |
number?
|
The maximum On-Duty time allowed in a day. Used for HOS Europe only |
options.hosMaxOnDutyTimeInWeek |
number?
|
The maximum On-Duty time allowed in a week. Used for HOS Europe only |
options.hosAdverseConditionException |
boolean?
|
a value indicating where adverse driving conditions are present. If so, consecutive driving an daily driving. HOS clock are extended by 2 hours due to the adverse driving condition exception. |
options.hosPOIStopsReturned |
boolean?
|
A value indicating whether POI Rest Stops will be returned, or only Lat/Lon Rest Stops will be returned. |
options.hosHOSWindowStart |
number?
|
The start time of the window during the trip may insert an HOS Rest Stop |
options.hosHOSWindowEnd |
number?
|
The end time of the window during the trip may insert an HOS Rest Stop |
options.maintainHeading |
boolean?
|
When this option is set, a vehicle will attempt to avoid u-turns at intermediate stops and instead leave the stop in the same direction it entered it. When using the school bus vehicle profiles, this option will be automatically set to true if not supplied. |
options.sideOfStreetAdherence |
Common.SideOfStreetAdherenceLevel?
|
Represents the levels of adherence that apply a cost to a route if its destination is on the opposite side of the street. |
options.governorSpeedLimit |
number?
|
Maximum average road speed to use in route calculations that overrides all other road speeds when they are above this value. |
options.useAvoidsAndFavors |
boolean?
|
Indicating whether or not to use avoids and favors |
options.useSites |
boolean?
|
Default:
false
|
options.vehicleProfile |
Common.TruckConfig?
|
Provides the ability to load a vehicle profile which includes vehicle dimensions, route costs and routing options for a specific vehicle class. This option replaces the vehicleType and SharedOptions.truckStyle. |
options.refrigerated |
boolean?
|
Indicates whether the vehicle is a refrigerated truck. |
options.fuelType |
Common.FuelType?
|
Fuel type |
options.fuelConsumption |
number?
|
Indicates the fuel consumption of the vehicle. |
options.trafficLookaheadDistance |
number?
|
Distance in miles for which we will gather traffic for the route. |
options.avoidState |
Array<string>?
|
A list of states are avoided, for example ['NJ', 'PA'] . ISO2 code. |
options.favorState |
Array<string>?
|
A list of states are in favor. |
options.favorCountry |
Array<string>?
|
A list of countries are in favor. |
options.includeTrimblePlaceIDs |
boolean?
|
Indicates use Trimble placeIds from while the processing route |
options.useCrossStreetTurnAvoidance |
boolean?
|
Turns avoid cross street turns logic on or off. |
options.congestionZonesOpen |
boolean?
|
? |
options.lowEmissionZonesOpen |
boolean?
|
? |
options.displayRestrictions |
Common.DisplayRestrictionsType?
|
? |
options.profileName |
string?
|
Profile name |
options.isDraggable |
boolean?
|
Default:
false
|
options.dragOptions |
DragRouteOptions?
|
Options for customizing route dragging behavior, such as snapping
the route path to a nearby road link that is visible. By default,
with dragging enabled, you can activate this snapping behavior by
holding the SHIFT key while dragging.
By adding a valid viaPointModifierKey property value, you can enable removing stops that are introduced by drag routing. It is better either enabling undo-redo feature or the removing stop feature. It is not recommended to use both features at the same time. Also be ware, update route function only takes LngLat or LngLatLike in an array, flags that indicating stops are generated by drag routing will be removed. After route update, no stops can be removed. After this option is set, it can't be changed such as using the update method. |
options.assetId |
string?
|
The ID of the asset (device, vehicle or driver) associated. |
options.estimatedTimeOpts |
string?
|
Estimated time options allow you to specify either a day of the week or a specific date and the time for which you would like you depart from your origin or arrive at your destination. |
options.useTraffic |
boolean?
|
Default:
false
Indicates whether or not use traffic which is only used in conjunction with fastest routing. |
options.includeVehicleRestrictedCleanupPoints |
boolean?
|
Boolean that designates if the customer wants the vehicle restricted cleanups to be separated from the main coordinate list and returned separately. |
options.trlType |
Common.TrailerType?
|
Default:
TrimbleMaps.Common.TrailerType.NONE
Type of the trailer. For Toll Detail reports in Europe.
|
options.trlCount |
number?
|
Default:
0
Number of trailers and semi-trailers. For Toll Detail reports in Europe. |
options.trlMaxHt |
string?
|
Max height of the trailer in feet and inches, or meters depending on units. For Toll Detail reports in Europe. |
options.trlMaxWt |
number?
|
Max weight of the trailer in pounds or kilograms depending on units. For Toll Detail reports in Europe. |
options.trlMaxAxles |
number?
|
Default:
1
Max number of axles on the trailer. Acceptable values are 1 - 8. For Toll Detail reports in Europe. |
options.isHybrid |
boolean?
|
Default:
false
Indicates whether vehicle has a hybrid engine. For Toll Detail reports in Europe. |
options.emiType |
Common.EmissionType?
|
Default:
TrimbleMaps.Common.EmissionType.EUROVI
The emission type of the engine. For Toll Detail reports in Europe.
|
options.minPoll |
boolean?
|
Default:
false
Indicates whether the vehicle is a minimum vehicle pollution. For Toll Detail reports in Europe. |
options.frameRoute |
boolean?
|
Default:
undefined
Indicates whether the center point and zoom level of the map will be adjusted to show the route in full frame. Only when it sets to false, the route will not be framed. |
options.showStops |
boolean?
|
Default:
undefined
Indicates whether the stops are displayed. After it is set, it can't be changed. When it sets to false, 1) stops will not be displayed, 2) originIcon, destinationIcon, and stopIcon will be ignored, 3) update function can be used to change route color, 4) it allows user to display custom icons, see examples on the Developer Portal. |
options.congestionZone |
Common.ZoneType?
|
Congestion zone value |
options.lowEmissionZone |
Common.ZoneType?
|
Low emission zone value |
options.ultraLowEmissionZone |
Common.ZoneType?
|
Ultra low emission zone value |
options.overrideClass |
Common.ClassOverride?
|
Default:
TrimbleMaps.Common.ClassOverride.NONE
Represents type of class overrides.
|
options.requestMethod |
Common.RequestMethod?
|
Default:
undefined
. Uses HTTP GET method as default. Set the request method to
POST
to use HTTP POST method. Not every route option is supported by
'GET' method.
|
options.frameOptions |
Object?
|
A Map#fitBounds options object used to frame the route on the map when frameRoute is set to true. Default is 50px padding. After this option is set, it can't be changed such as using the update method. |
options.showArrows |
boolean?
|
Default
false
Indicates whether direction arrows are drawn on top of the route
line.
|
options.arrowOptions |
ArrowOptions?
|
Options for customizing the vizualization of route arrows. |
options.isVisible |
boolean?
|
Default:
true
Indicates whether the route will be visible when added to the map.
|
options.hubRouting |
boolean?
|
Default:
false
Indicates whether or not to enable hub routing. Set to true to
enable hub routing. When hub routing is enabled, drag routing and
route optimizaion will be disabled.
|
Example
var route = new TrimbleMaps.Route({
routeId: 'myRoute',
routeWidth: 8, // or {stops: [[10, 7],[15, 9],[19, 11]]}
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.499440),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
],
routeType: TrimbleMaps.Common.RouteType.SHORTEST,
frameRoute: false,
showStops: false,
overrideClass: TrimbleMaps.Common.ClassOverride.FIFTY_THREE,
requestMethod: TrimbleMaps.Common.RequestMethod.POST
})
.addTo(map);
Instance Members
Moves route layers to a different z-position. The route will be inserted
before the layer with
ID beforeId
, or appended on the top of the map if
beforeId
is omitted.
moveLayer(beforeId: string?): Route
Parameters
beforeId
(string?)
Optional ID of an existing layer to insert before
Returns
Route
:
this
Example
const myRoute1 = new TrimbleMaps.Route();
myRoute1.addTo(map);
myRoute1.moveLayer('layerId');
Updates the route. It particularly updates route path, stop icons, route color, route opacity, route width, route arrow, drag routing. If more controlling over route stops styling is desirable, instead of using this function, construct a route with showStops setting to false, then adding custom stops icons uses addStopIcon function and styling them uses styleStopIcons function.
update(options: RouteOptions)
Parameters
options
(RouteOptions)
The route options to be updated.
Gets reports for the route options
getReports(options: RouteOptions)
Parameters
options
(RouteOptions)
The route options used for the reports.
Changes stop icons styles. Following properties are assigned internally: id, type, source, layout['icon-image'], layout['text-font']
styleStopIcons(style: Object)
Parameters
Undo route drag
undo()
Redo route drag
redo()
Enables route undo, redo stack. It is better either enabling undo-redo feature or the removing stop feature. It is not recommended to use both features at the same time.
enableRouteStack()
Disables route undo, redo stack.
disableRouteStack()
Events
Fired when a route is altered by dragging. Instead of letting the API handles the stop insertion, user utilizes a custom event listener to insert the stop. This event is not available when drag route is disabled.
stopInserting
Type: Object
Properties
event
(Event)
: a new stop and available insertion positions.
Example
// Create a route
const myRoute = new TrimbleMaps.Route(routeOptions);
// Set an event listener
myRoute.on('stopInserting', function(e) {
myRoute.getRouteWithNewStop(e.newStop, e.routeLegPositions[e.routeLegPositions.length - 1]);
});
StopOptions
Stop options used to provide more information about each stop.
Note: When using StopOptions, the requestMethod parameter of RouteOptions will be ignored and the request type will be POST.
StopOptions
Type: Object
Properties
id
(string)
: String used for the id of the stop.
label
(string)
: String used for the label of the stop. This label will appear in reports.
lngLat
(LngLatLike)
: Location of the stop (required).
address
(Object)
: Address object of the stop.
costs
(Object)
: Object detailing cost information related to the stop
isViaPoint
(boolean)
ArrowOptions
Arrow options are used to define the appearance of arrows shown on the route when showArrows is set to true.
ArrowOptions
Type: Object
Properties
DragRouteOptions
DragRouteOptions
Type: Object
Properties
snapMode
(Common.SnapMode)
snapKey
(Common.SnapKey)
viaPointModifierKey
(Common.ViaPointModifierKey)
Helper classes to access web services.
Services
Geocoder
Geocoder
Geocoder
Static Members
Geocode
geocode
Parameters
Options
(GeocodeOptions)
Example
var geocodeLocation = TrimbleMaps.Geocoder.geocode({
address: {
addr: '1 Independence Way',
city: 'Princeton',
state: 'NJ',
zip: '08540',
region: TrimbleMaps.Common.Region.NA
},
listSize: 1,
success: function(response) {
console.log(response);
},
failure: function(response) {
console.log(response);
}
});
Reverse Geocode
reverseGeocode
Parameters
Options
(ReverseGeocodeOptions)
Example
var reverseGeocodeLocation = TrimbleMaps.Geocoder.reverseGeocode({
lonLat: new TrimbleMaps.LngLat(-122.31693, 47.60784),
region: TrimbleMaps.Common.Region.NA,
success: function(response) {
console.log(response);
},
failure: function(response) {
console.log(response);
}
});
Search
Search
Search
Static Members
Single Search
singleSearch
Parameters
options
(SingleSearchOptions)
Search options
Name | Type | Description |
---|---|---|
options.query |
string?
|
String indicating the text to search for. This is the only required property. |
options.region |
string?
|
Search reqgion. Defaul to NA. |
options.maxResults |
number?
|
Limits search results by the specified number. Must be a value between 1 and 100. |
options.currentLonLat |
LngLat?
|
The current longitude and latitude. |
options.excludeResultsFor |
string?
|
A comma-separated list of InterpTypes to exclude from the search. |
options.includeOnly |
string?
|
A comma-separated list of InterpTypes to include in the search response. |
options.poiCategories |
string?
|
A comma-separated list of Points of Interest (POI) category names by which you want to filter all POI results. |
options.countries |
string?
|
A comma-separated list of country codes by which you want to filter all results. |
options.countryType |
string?
|
The standard for country abbreviations: ISO, FIPS, GENC2, and GENC3. |
options.states |
string?
|
A comma-separated list of state abbreviations by which you want to filter all results. |
options.include |
string?
|
Set to include=Meta to include additional metadata in your results, such as road grid and link information as well as the confidence level of the search results. |
options.useCustomPlaces |
boolean?
|
If set to true, returns any custom places in the account where the location’s PlaceId or PlaceName starts with the query string. |
options.separateHN |
boolean?
|
Sets whether the house number should be returned as a separate field from the rest of the street address. Default is false. |
options.getAllHNRanges |
boolean?
|
If set to true, all potential house number ranges will be returned for a particular street match. Default is false. |
options.includeTrimblePlaceIds |
boolean?
|
Set to true to return the TrimblePlaceId, PlaceName and SiteName for a location, if they exist. Default is false. |
options.lang |
string?
|
The language to use in results. U.S. English is the default. |
options.matchNamedRoadsOnly |
boolean?
|
When looking up coordinates, this forces reverse geocoding to match named roads only. Applicable when performing a Reverse geocode search. |
options.maxCleanupMiles |
number?
|
When looking up coordinates, this sets a maximum radius, in miles, in which to find the closest matching road. Applicable when performing a Reverse geocode search. |
options.heading |
number?
|
Used to determine which road link to snap to. For instance, when crossing a highway. Values are: 0 - North, 90 - East, 180 - South, 270 - East. Applicable when performing a Reverse geocode search. |
Returns
any
:
Promise
Example
const searchPromise = TrimbleMaps.Search.singleSearch({
query: '1 independence way, princeton, nj, 08540',
currentLonLat: new TrimbleMaps.LngLat(-74.600291, 40.360869),
excludeResultsFor: 'POI, POItype',
includeOnly: 'Country, State, County, City, POBox, Zip',
poiCategories: 'Airport, bank, CAT scales',
countries: 'US',
countryType: 'ISO',
states: 'NJ',
include: 'Meta',
useCustomPlaces: true,
separateHN: false,
getAllHNRanges: false,
includeTrimblePlaceIds: true,
lang: 'en-us',
matchNamedRoadsOnly: true,
maxCleanupMiles: 10,
heading: 90
});
Routing
Routing
Routing
Static Members
Derived route path using POST
postDerivedRoutePath
Parameters
Options
(ReduceTripOptions)
Returns
Cancelable
:
Cancelable request
Example
const options = {
routePings: [
new TrimbleMaps.LngLat(-118.309434, 33.714154),
new TrimbleMaps.LngLat(-118.316631, 33.721061)
],
offRouteMiles: 0,
highwayOnly: false,
reportType: TrimbleMaps.Common.ReportType.MILEAGE, // or TrimbleMaps.Common.ReportType.DETAIL
region: TrimbleMaps.Common.Region.NA,
routingOptions: {
vehicleType: TrimbleMaps.Common.VehicleType.TRUCK,
routeType: TrimbleMaps.Common.RouteType.PRACTICAL,
routeOptimization: TrimbleMaps.Common.RouteOptimization.NONE,
tollDiscourage: false,
afSetIDs: [24, 133, 204],
afSetNames: ['Highways', 'TollRoads', 'Malls'],
bordersOpen: true,
overrideRestrict: false,
highwayOnly: false,
hazMatTypes: [TrimbleMaps.Common.HazMatType.NONE],
distanceUnits: TrimbleMaps.Common.DistanceUnit.MILES,
trkUnits: TrimbleMaps.Common.TruckUnit.ENGLISH,
trkHeight: '13\u00276\"',
trkLength: '48\u00270\"',
trkWidth: '96\"',
trkWeight: '80000',
trkAxles: 5,
useSites: false,
overrideClass: TrimbleMaps.Common.ClassOverride.NONE
},
extendedOptions: {
estimatedTimeOptions: {
eTAETDType: TrimbleMaps.Common.ETAETDType.DEPART,
dateOption: TrimbleMaps.Common.DateOption.SPECIFIC,
dateAndTime: {
calendarDate: '4/23/2014',
dayOfWeek: TrimbleMaps.Common.DayOfWeek.SUNDAY,
timeOfDay: '6:00 AM',
timeZone: TrimbleMaps.Common.TimeZone.LOCAL
}
},
useTraffic: true,
truckStyle: TrimbleMaps.Common.TruckConfig.NONE,
includeVehicleRestrictedCleanupPoints: false
},
callback: function(error, response) {
if(error === null) {
console.log('success', response);
} else {
console.log('failure', error);
}
}
};
const derivedRoutePath = TrimbleMaps.Routing.postDerivedRoutePath(options);
Derived route path reports (mileage or detail) using POST
postDerivedRouteReports
Parameters
Options
(ReduceTripOptions)
Returns
Cancelable
:
Cancelable request
Example
const options = {
routePings: [
new TrimbleMaps.LngLat(-118.309434, 33.714154),
new TrimbleMaps.LngLat(-118.316631, 33.721061)
],
offRouteMiles: 0,
highwayOnly: false,
reportType: TrimbleMaps.Common.ReportType.MILEAGE, // or TrimbleMaps.Common.ReportType.DETAIL
region: TrimbleMaps.Common.Region.NA,
routingOptions: {
vehicleType: TrimbleMaps.Common.VehicleType.TRUCK,
routeType: TrimbleMaps.Common.RouteType.PRACTICAL,
routeOptimization: TrimbleMaps.Common.RouteOptimization.NONE,
tollDiscourage: false,
afSetIDs: [24, 133, 204],
afSetNames: ['Highways', 'TollRoads', 'Malls'],
bordersOpen: true,
overrideRestrict: false,
highwayOnly: false,
hazMatTypes: [TrimbleMaps.Common.HazMatType.NONE],
distanceUnits: TrimbleMaps.Common.DistanceUnit.MILES,
trkUnits: TrimbleMaps.Common.TruckUnit.ENGLISH,
trkHeight: '13\u00276\"',
trkLength: '48\u00270\"',
trkWidth: '96\"',
trkWeight: '80000',
trkAxles: 5,
useSites: false,
overrideClass: TrimbleMaps.Common.ClassOverride.NONE
},
extendedOptions: {
estimatedTimeOptions: {
eTAETDType: TrimbleMaps.Common.ETAETDType.DEPART,
dateOption: TrimbleMaps.Common.DateOption.SPECIFIC,
dateAndTime: {
calendarDate: '4/23/2014',
dayOfWeek: TrimbleMaps.Common.DayOfWeek.SUNDAY,
timeOfDay: '6:00 AM',
timeZone: TrimbleMaps.Common.TimeZone.LOCAL
}
},
useTraffic: true,
truckStyle: TrimbleMaps.Common.TruckConfig.NONE,
includeVehicleRestrictedCleanupPoints: false
},
callback: function(error, response) {
if (error === null) {
console.log('success', response);
} else {
console.log('failure', error);
}
}
};
const derivedRouteReports = TrimbleMaps.Routing.postDerivedRouteReports(options);
POST request retrieves a list of road surface conditions at each point of a route path. The conditions are returned in an integer array where 1 - Dry road 2 - Wet road 3 - Ice/snow 4 - Mix water/snow 5 - Dew 6 - Melting snow 7 - Frost 8 - Icing rain 99 - Not in range
postRoadSurfaceRoute
Parameters
options
(RoadSurfaceRouteOptions)
Road surface route options
Returns
Cancelable
:
Cancelable request.
Example
const options = {
routeDuration: 3155,
provider: 'RC1',
routePath: [[-74.437916,39.362518],[-74.43799,39.36264],[-74.43803,39.362718],[-74.438961,39.362649],[-74.438942,39.362469]],
callback: function(error, response) {
if(error === null) {
// sample response {"data":"[1,1,1,1,1]"}
console.log('success', response);
} else {
console.log('failure', error);
}
}
};
const request = TrimbleMaps.Routing.postRoadSurfaceRoute(options);
Controls, markers, and popups add new user interface elements to the map.
User Interface
IControl
Interface for interactive controls added to the map. This is a specification for implementers to model: it is not an exported method or class.
Controls must implement onAdd
and onRemove
, and must own an
element, which is often a div
element. To use the JavaScript Maps SDK's
default control styling, add the trimblemaps-ctrl
class to your control's
node.
IControl
Example
// Control implemented as ES6 class
class HelloWorldControl {
onAdd(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'trimblemaps-ctrl';
this._container.textContent = 'Hello, world';
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
// Control implemented as ES5 prototypical class
function HelloWorldControl() { }
HelloWorldControl.prototype.onAdd = function(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'trimblemaps-ctrl';
this._container.textContent = 'Hello, world';
return this._container;
};
HelloWorldControl.prototype.onRemove = function () {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
};
Instance Members
Register a control on the map and give it a chance to register event listeners and resources. This method is called by Map#addControl internally.
onAdd(map: Map): HTMLElement
Parameters
map
(Map)
the Map this control will be added to
Returns
HTMLElement
:
The control's container element. This should
be created by the control and returned by onAdd without being attached
to the DOM: the map will insert the control's element into the DOM
as necessary.
Unregister a control on the map and give it a chance to detach event listeners and resources. This method is called by Map#removeControl internally.
onRemove(map: Map): undefined
Parameters
map
(Map)
the Map this control will be removed from
Returns
undefined
:
there is no required return value for this method
Optionally provide a default position for this control. If this method
is implemented and Map#addControl is called
without the position
parameter, the value returned by getDefaultPosition will be used as the
control's position.
getDefaultPosition(): string
Returns
string
:
a control position, one of the values valid in addControl.
NavigationControl
A NavigationControl
control contains zoom buttons and a compass.
new NavigationControl(options: Object?)
Parameters
options
(Object?)
Name | Type | Description |
---|---|---|
options.showCompass |
Boolean
(default: true )
|
If
true
the compass button is included.
|
options.showZoom |
Boolean
(default: true )
|
If
true
the zoom-in and zoom-out buttons are included.
|
options.visualizePitch |
Boolean
(default: false )
|
If
true
the pitch is visualized by rotating X-axis of compass.
|
Example
var nav = new TrimbleMaps.NavigationControl();
map.addControl(nav, 'top-left');
GeolocateControl
A GeolocateControl
control provides a button that uses the browser's
geolocation
API to locate the user on the map.
Not all browsers support geolocation, and some users may disable the feature. Geolocation support for modern browsers including Chrome requires sites to be served over HTTPS. If geolocation support is not available, the GeolocateControl will show as disabled.
The zoom level applied will depend on the accuracy of the geolocation provided by the device.
The GeolocateControl has two modes. If trackUserLocation
is
false
(default) the control acts as a button, which when pressed will set
the map's camera to target the user location. If the user moves, the map won't update.
This is most suited for the desktop. If trackUserLocation
is
true
the control acts as a toggle button that when active the user's
location is actively monitored for changes. In this mode the GeolocateControl has three
interaction states:
- active - the map's camera automatically updates as the user's location changes,
keeping the location dot in the center. Initial state and upon clicking the
GeolocateControl
button. - passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.
- disabled - occurs if Geolocation is not available, disabled or denied.
These interaction states can't be controlled programmatically, rather they are set based on user interactions.
new GeolocateControl(options: Object?)
Extends Evented
Parameters
options
(Object?)
Name | Type | Description |
---|---|---|
options.positionOptions |
Object
(default:
{enableHighAccuracy:false,timeout:6000} )
|
A Geolocation API PositionOptions object. |
options.fitBoundsOptions |
Object
(default: {maxZoom:15} )
|
A
Map#fitBounds
options object to use when the map is panned and zoomed to the
user's location. The default is to use a
maxZoom
of 15 to limit how far the map will zoom in for very accurate
locations.
|
options.trackUserLocation |
Object
(default: false )
|
If
true
the Geolocate Control becomes a toggle button and when active the
map will receive updates to the user's location as it changes.
|
options.showAccuracyCircle |
Object
(default: true )
|
By default, if showUserLocation is
true
, a transparent circle will be drawn around the user location
indicating the accuracy (95% confidence level) of the user's
location. Set to
false
to disable. Always disabled when showUserLocation is
false
.
|
options.showUserLocation |
Object
(default: true )
|
By default a dot will be shown on the map at the user's location.
Set to
false
to disable.
|
Example
map.addControl(new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
Instance Members
Programmatically request and move the map to the user's location.
trigger(): boolean
Returns
boolean
:
Returns
false
if called before control was added to a map, otherwise returns
true
.
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
geolocate.trigger();
});
Events
Fired on each Geolocation API position update which returned as success.
geolocate
Properties
data
(Position)
: The returned
Position
object from the callback in
Geolocation.getCurrentPosition()
or
Geolocation.watchPosition()
.
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a geolocate event occurs.
geolocate.on('geolocate', function() {
console.log('A geolocate event has occurred.')
});
Fired on each Geolocation API position update which returned as an error.
error
Properties
data
(PositionError)
: The returned
PositionError
object from the callback in
Geolocation.getCurrentPosition()
or
Geolocation.watchPosition()
.
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an error event occurs.
geolocate.on('error', function() {
console.log('An error event has occurred.')
});
Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds.
outofmaxbounds
Properties
data
(Position)
: The returned
Position
object from the callback in
Geolocation.getCurrentPosition()
or
Geolocation.watchPosition()
.
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an outofmaxbounds event occurs.
geolocate.on('outofmaxbounds', function() {
console.log('An outofmaxbounds event has occurred.')
});
Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes).
trackuserlocationstart
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationstart event occurs.
geolocate.on('trackuserlocationstart', function() {
console.log('A trackuserlocationstart event has occurred.')
});
Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.
trackuserlocationend
Example
// Initialize the geolocate control.
var geolocate = new TrimbleMaps.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationend event occurs.
geolocate.on('trackuserlocationend', function() {
console.log('A trackuserlocationend event has occurred.')
});
AttributionControl
An AttributionControl
control presents the map's attribution information.
new AttributionControl(options: Object?)
Parameters
Example
var map = new TrimbleMaps.Map({attributionControl: false})
.addControl(new TrimbleMaps.AttributionControl({
compact: true
}));
ScaleControl
A ScaleControl
control displays the ratio of a distance on the map to the
corresponding distance on the ground.
new ScaleControl(options: Object?)
Parameters
Example
var scale = new TrimbleMaps.ScaleControl({
maxWidth: 80,
unit: 'imperial'
});
map.addControl(scale);
scale.setUnit('metric');
Instance Members
Set the scale's unit of the distance
setUnit(unit: Unit)
Parameters
unit
(Unit)
Unit of the distance (
'imperial'
,
'metric'
or
'nautical'
).
FullscreenControl
A FullscreenControl
control contains a button for toggling the map in and
out of fullscreen mode.
new FullscreenControl(options: Object?)
Parameters
options
(Object?)
Name | Type | Description |
---|---|---|
options.container |
HTMLElement?
|
container
is the
compatible
DOM element
which should be made full screen. By default, the map container
element will be made full screen.
|
Example
map.addControl(new TrimbleMaps.FullscreenControl());
Popup
A popup component.
new Popup(options: Object?)
Extends Evented
Parameters
options
(Object?)
Name | Type | Description |
---|---|---|
options.closeButton |
boolean
(default: true )
|
If
true
, a close button will appear in the
top right corner of the popup.
|
options.closeOnClick |
boolean
(default: true )
|
If
true
, the popup will closed when the
map is clicked.
|
options.closeOnMove |
boolean
(default: false )
|
If
true
, the popup will closed when the
map moves.
|
options.anchor |
string?
|
A string indicating the part of the Popup that should
be positioned closest to the coordinate set via
Popup#setLngLat
.
Options are
'center'
,
'top'
,
'bottom'
,
'left'
,
'right'
,
'top-left'
,
'top-right'
,
'bottom-left'
, and
'bottom-right'
. If unset the anchor will be
dynamically set to ensure the popup falls within the map container
with a preference
for
'bottom'
.
|
options.offset |
(number | PointLike | Object)?
|
A pixel offset applied to the popup's location specified as: |
options.className |
string?
|
Space-separated CSS class names to add to popup container |
options.maxWidth |
string
(default: '240px' )
|
A string that sets the CSS property of the popup's maximum width,
eg
'300px'
.
To ensure the popup resizes to fit its content, set this property to
'none'
.
Available values can be found here:
https://developer.mozilla.org/en-US/docs/Web/CSS/max-width
|
Example
var markerHeight = 50, markerRadius = 10, linearOffset = 25;
var popupOffsets = {
'top': [0, 0],
'top-left': [0,0],
'top-right': [0,0],
'bottom': [0, -markerHeight],
'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
'left': [markerRadius, (markerHeight - markerRadius) * -1],
'right': [-markerRadius, (markerHeight - markerRadius) * -1]
};
var popup = new TrimbleMaps.Popup({offset:popupOffsets})
.setLngLat(e.lngLat)
.setHTML("<h1>Hello World!</h1>")
.setMaxWidth("300px")
.addTo(map);
Instance Members
Returns the geographical location of the popup's anchor.
The longitude of the result may differ by a multiple of 360 degrees from
the longitude previously
set by setLngLat
because Popup
wraps the
anchor longitude across copies of the world to keep
the popup on screen.
getLngLat(): LngLat
Returns
LngLat
:
The geographical location of the popup's anchor.
Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.
setLngLat(lnglat: LngLatLike): Popup
Parameters
lnglat
(LngLatLike)
The geographical location to set as the popup's anchor.
Returns
Popup
:
this
Tracks the popup anchor to the cursor position on screens with a pointer
device (it will be hidden on touchscreens). Replaces the
setLngLat
behavior.
For most use cases, set closeOnClick
and
closeButton
to false
.
trackPointer(): Popup
Returns
Popup
:
this
Example
var popup = new TrimbleMaps.Popup({ closeOnClick: false, closeButton: false })
.setHTML("<h1>Hello World!</h1>")
.trackPointer()
.addTo(map);
Returns the Popup
's HTML element.
getElement(): HTMLElement
Returns
HTMLElement
:
element
Example
// Change the `Popup` element's font size
var popup = new TrimbleMaps.Popup()
.setLngLat([-96, 37.8])
.setHTML("<p>Hello World!</p>")
.addTo(map);
var popupElem = popup.getElement();
popupElem.style.fontSize = "25px";
Sets the popup's content to a string of text.
This function creates a Text node in the DOM, so it cannot insert raw HTML. Use this method for security against XSS if the popup content is user-provided.
setText(text: string): Popup
Parameters
text
(string)
Textual content for the popup.
Returns
Popup
:
this
Example
var popup = new TrimbleMaps.Popup()
.setLngLat(e.lngLat)
.setText('Hello, world!')
.addTo(map);
Sets the popup's content to the HTML provided as a string.
This method does not perform HTML filtering or sanitization, and must be used only with trusted content. Consider Popup#setText if the content is an untrusted text string.
setHTML(html: string): Popup
Parameters
html
(string)
A string representing HTML content for the popup.
Returns
Popup
:
this
Example
var popup = new TrimbleMaps.Popup()
.setLngLat(e.lngLat)
.setHTML("<h1>Hello World!</h1>")
.addTo(map);
Sets the popup's maximum width. This is setting the CSS property
max-width
.
Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width
setMaxWidth(maxWidth: string): Popup
Parameters
maxWidth
(string)
A string representing the value for the maximum width.
Returns
Popup
:
this
Sets the popup's content to the element provided as a DOM node.
setDOMContent(htmlNode: Node): Popup
Parameters
htmlNode
(Node)
A DOM node to be used as content for the popup.
Returns
Popup
:
this
Example
// create an element with the popup content
var div = window.document.createElement('div');
div.innerHTML = 'Hello, world!';
var popup = new TrimbleMaps.Popup()
.setLngLat(e.lngLat)
.setDOMContent(div)
.addTo(map);
Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.
toggleClassName(className: string): boolean
Parameters
className
(string)
Non-empty string with CSS class name to add/remove
Returns
boolean
:
if the class was removed return false, if class was added, then return true
Example
let popup = new TrimbleMaps.Popup()
popup.toggleClassName('toggleClass')
Events
Fired when the popup is opened manually or programatically.
open
Type: Object
Properties
popup
(Popup)
: object that was opened
Example
// Create a popup
var popup = new TrimbleMaps.Popup();
// Set an event listener that will fire
// any time the popup is opened
popup.on('open', function(){
console.log('popup was opened');
});
Fired when the popup is closed manually or programatically.
close
Type: Object
Properties
popup
(Popup)
: object that was closed
Example
// Create a popup
var popup = new TrimbleMaps.Popup();
// Set an event listener that will fire
// any time the popup is closed
popup.on('close', function(){
console.log('popup was closed');
});
Marker
Creates a marker component
new Marker(options: Object?, legacyOptions: Options?)
Extends Evented
Parameters
options
(Object?)
Name | Type | Description |
---|---|---|
options.element |
HTMLElement?
|
DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker. |
options.anchor |
string
(default: 'center' )
|
A string indicating the part of the Marker that should be positioned
closest to the coordinate set via
Marker#setLngLat
.
Options are
'center'
,
'top'
,
'bottom'
,
'left'
,
'right'
,
'top-left'
,
'top-right'
,
'bottom-left'
, and
'bottom-right'
.
|
options.offset |
PointLike?
|
The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up. |
options.color |
string
(default: '#3FB1CE' )
|
The color to use for the default marker if options.element is not provided. The default is light blue. |
options.scale |
number
(default: 1 )
|
The scale to use for the default marker if options.element is not
provided. The default scale corresponds to a height of
41px
and a width of
27px
.
|
options.draggable |
boolean
(default: false )
|
A boolean indicating whether or not a marker is able to be dragged to a new position on the map. |
options.rotation |
number
(default: 0 )
|
The rotation angle of the marker in degrees, relative to its
respective
rotationAlignment
setting. A positive value will rotate the marker clockwise.
|
options.pitchAlignment |
string
(default: 'auto' )
|
map
aligns the
Marker
to the plane of the map.
viewport
aligns the
Marker
to the plane of the viewport.
auto
automatically matches the value of
rotationAlignment
.
|
options.rotationAlignment |
string
(default: 'auto' )
|
map
aligns the
Marker
's rotation relative to the map, maintaining a bearing as the map
rotates.
viewport
aligns the
Marker
's rotation relative to the viewport, agnostic to map rotations.
auto
is equivalent to
viewport
.
|
legacyOptions
(Options?)
Example
var marker = new TrimbleMaps.Marker()
.setLngLat([30.5, 50.5])
.addTo(map);
Instance Members
Get the marker's geographical location.
The longitude of the result may differ by a multiple of 360 degrees from
the longitude previously
set by setLngLat
because Marker
wraps the
anchor longitude across copies of the world to keep
the marker on screen.
getLngLat(): LngLat
Returns
LngLat
:
A
LngLat
describing the marker's location.
Example
// Store the marker's longitude and latitude coordinates in a variable
var lngLat = marker.getLngLat();
// Print the marker's longitude and latitude values in the console
console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )
Returns the Marker
's HTML element.
getElement(): HTMLElement
Returns
HTMLElement
:
element
Returns the Popup instance that is bound to the Marker.
getPopup(): Popup
Returns
Popup
:
popup
Example
var marker = new TrimbleMaps.Marker()
.setLngLat([0, 0])
.setPopup(new TrimbleMaps.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);
console.log(marker.getPopup()); // return the popup instance
Opens or closes the Popup instance that is bound to the Marker, depending on the current state of the Popup.
togglePopup(): Marker
Returns
Marker
:
this
Example
var marker = new TrimbleMaps.Marker()
.setLngLat([0, 0])
.setPopup(new TrimbleMaps.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);
marker.togglePopup(); // toggle popup open or closed
Sets the rotation
property of the marker.
setRotation(rotation: number): Marker
Parameters
rotation
(number
= 0
)
The rotation angle of the marker (clockwise, in degrees),
relative to its respective
Marker#setRotationAlignment
setting.
Returns
Marker
:
this
Events
Handlers add different kinds of interactivity to the map -
mouse interactivity, touch interactions, and other
gestures.
User Interaction Handlers
BoxZoomHandler
The BoxZoomHandler
allows the user to zoom the map to fit within a bounding
box.
The bounding box is defined by clicking and holding shift
while dragging
the cursor.
new BoxZoomHandler(map: Map, options: {clickTolerance: number})
Parameters
Instance Members
ScrollZoomHandler
The ScrollZoomHandler
allows the user to zoom the map by scrolling.
new ScrollZoomHandler(map: Map, handler: HandlerManager)
Parameters
map
(Map)
handler
(HandlerManager)
Instance Members
DragPanHandler
The DragPanHandler
allows the user to pan the map by clicking and dragging
the cursor.
new DragPanHandler(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler)
Parameters
Instance Members
Enables the "drag to pan" interaction.
enable(options: Object?)
Parameters
options
(Object?)
Options object
Name | Type | Description |
---|---|---|
options.linearity |
number
(default: 0 )
|
factor used to scale the drag velocity |
options.easing |
Function
(default:
bezier(0,0,0.3,1) )
|
easing function applled to
map.panTo
when applying the drag.
|
options.maxSpeed |
number
(default: 1400 )
|
the maximum value of the drag velocity. |
options.deceleration |
number
(default: 2500 )
|
the rate at which the speed reduces after the pan ends. |
Example
map.dragPan.enable();
map.dragPan.enable({
linearity: 0.3,
easing: bezier(0, 0, 0.3, 1),
maxSpeed: 1400,
deceleration: 2500,
});
Disables the "drag to pan" interaction.
disable()
Example
map.dragPan.disable();
DragRotateHandler
The DragRotateHandler
allows the user to rotate the map by clicking and
dragging the cursor while holding the right mouse button or ctrl
key.
new DragRotateHandler(options: Object?, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler)
Parameters
Instance Members
KeyboardHandler
The KeyboardHandler
allows the user to zoom, rotate, and pan the map using
the following keyboard shortcuts:
=
/+
: Increase the zoom level by 1.Shift-=
/Shift-+
: Increase the zoom level by 2.-
: Decrease the zoom level by 1.Shift--
: Decrease the zoom level by 2.- Arrow keys: Pan by 100 pixels.
Shift+⇢
: Increase the rotation by 15 degrees.Shift+⇠
: Decrease the rotation by 15 degrees.Shift+⇡
: Increase the pitch by 10 degrees.Shift+⇣
: Decrease the pitch by 10 degrees.
new KeyboardHandler()
DoubleClickZoomHandler
The DoubleClickZoomHandler
allows the user to zoom the map at a point by
double clicking or double tapping.
new DoubleClickZoomHandler(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler)
Parameters
clickZoom
(ClickZoomHandler)
TapZoom
(TapZoomHandler)
Instance Members
TouchZoomRotateHandler
The TouchZoomRotateHandler
allows the user to zoom and rotate the map by
pinching on a touchscreen.
They can zoom with one finger by double tapping and dragging. On the second tap, hold the finger down and drag up or down to zoom in or out.
new TouchZoomRotateHandler(el: HTMLElement, touchZoom: TouchZoomHandler, touchRotate: TouchRotateHandler, tapDragZoom: TapDragZoomHandler)
Parameters
el
(HTMLElement)
touchZoom
(TouchZoomHandler)
touchRotate
(TouchRotateHandler)
tapDragZoom
(TapDragZoomHandler)
Instance Members
Enables the "pinch to rotate and zoom" interaction.
enable(options: Object?)
Parameters
Example
map.touchZoomRotate.enable();
map.touchZoomRotate.enable({ around: 'center' });
Disables the "pinch to rotate and zoom" interaction.
disable()
Example
map.touchZoomRotate.disable();
Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" interaction enabled.
disableRotation()
Example
map.touchZoomRotate.disableRotation();
Enables the "pinch to rotate" interaction.
enableRotation()
Example
map.touchZoomRotate.enable();
map.touchZoomRotate.enableRotation();
TouchPitchHandler
The TouchPitchHandler
allows the user to pitch the map by dragging up and
down with two fingers.
new TouchPitchHandler()
Extends TwoTouchHandler
Instance Members
Returns a Boolean indicating whether the "drag to pitch" interaction is enabled.
isEnabled
Returns
boolean
:
true
if the "drag to pitch" interaction is enabled.
Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used.
isActive
Returns
boolean
:
true
if the "drag to pitch" interaction is active.
Enables the "drag to pitch" interaction.
enable
Example
map.touchPitch.enable();
Disables the "drag to pitch" interaction.
disable
Example
map.touchPitch.disable();
Sources specify the geographic features to be rendered on the map. Source
objects may be obtained from
Sources
Map#getSource
.
GeoJSONSource
A source containing GeoJSON.
new GeoJSONSource(id: string, options: any, dispatcher: Dispatcher, eventedParent: Evented)
Extends Evented
Parameters
Example
map.addSource('some id', {
type: 'geojson',
data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
});
map.addSource('some id', {
type: 'geojson',
data: {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
-76.53063297271729,
39.18174077994108
]
}
}]
}
});
map.getSource('some id').setData({
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": { "name": "Null Island" },
"geometry": {
"type": "Point",
"coordinates": [ 0, 0 ]
}
}]
});
Instance Members
Sets the GeoJSON data and re-renders the map.
setData(data: (Object | string)): GeoJSONSource
Parameters
Returns
GeoJSONSource
:
this
For clustered sources, fetches the zoom at which the given cluster expands.
getClusterExpansionZoom(clusterId: number, callback: Callback<number>): GeoJSONSource
Parameters
callback
(Callback<number>)
A callback to be called when the zoom value is retrieved (
(error, zoom) => { ... }
).
Returns
GeoJSONSource
:
this
For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
getClusterChildren(clusterId: number, callback: Callback<Array<GeoJSONFeature>>): GeoJSONSource
Parameters
callback
(Callback<Array<GeoJSONFeature>>)
A callback to be called when the features are retrieved (
(error, features) => { ... }
).
Returns
GeoJSONSource
:
this
For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback<Array<GeoJSONFeature>>): GeoJSONSource
Parameters
limit
(number)
The maximum number of features to return.
offset
(number)
The number of features to skip (e.g. for pagination).
callback
(Callback<Array<GeoJSONFeature>>)
A callback to be called when the features are retrieved (
(error, features) => { ... }
).
Returns
GeoJSONSource
:
this
Example
// Retrieve cluster leaves on click
map.on('click', 'clusters', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['clusters']
});
var clusterId = features[0].properties.cluster_id;
var pointCount = features[0].properties.point_count;
var clusterSource = map.getSource('clusters');
clusterSource.getClusterLeaves(clusterId, pointCount, 0, function(error, features) {
// Print cluster leaves in the console
console.log('Cluster leaves:', error, features);
})
});
VideoSource
A data source containing video.
new VideoSource(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented)
Extends ImageSource
Parameters
Example
// add to map
map.addSource('some id', {
type: 'video',
url: [
'https://www.website.com/blog/assets/baltimore-smoke.mp4',
'https://www.website.com/blog/assets/baltimore-smoke.webm'
],
coordinates: [
[-76.54, 39.18],
[-76.52, 39.18],
[-76.52, 39.17],
[-76.54, 39.17]
]
});
// update
var mySource = map.getSource('some id');
mySource.setCoordinates([
[-76.54335737228394, 39.18579907229748],
[-76.52803659439087, 39.1838364847587],
[-76.5295386314392, 39.17683392507606],
[-76.54520273208618, 39.17876344106642]
]);
map.removeSource('some id'); // remove
Instance Members
Pauses the video.
pause()
Plays the video.
play()
Returns the HTML video
element.
getVideo(): HTMLVideoElement
Returns
HTMLVideoElement
:
The HTML
video
element.
Sets the video's coordinates and re-renders the map.
setCoordinates(): VideoSource
Returns
VideoSource
:
this
ImageSource
A data source containing an image.
new ImageSource(id: string, options: (ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification), dispatcher: Dispatcher, eventedParent: Evented)
Extends Evented
Parameters
id
(string)
options
((ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification))
dispatcher
(Dispatcher)
eventedParent
(Evented)
Example
// add to map
map.addSource('some id', {
type: 'image',
url: 'https://www.website.com/images/foo.png',
coordinates: [
[-76.54, 39.18],
[-76.52, 39.18],
[-76.52, 39.17],
[-76.54, 39.17]
]
});
// update coordinates
var mySource = map.getSource('some id');
mySource.setCoordinates([
[-76.54335737228394, 39.18579907229748],
[-76.52803659439087, 39.1838364847587],
[-76.5295386314392, 39.17683392507606],
[-76.54520273208618, 39.17876344106642]
]);
// update url and coordinates simultaneously
mySource.updateImage({
url: 'https://www.website.com/images/bar.png',
coordinates: [
[-76.54335737228394, 39.18579907229748],
[-76.52803659439087, 39.1838364847587],
[-76.5295386314392, 39.17683392507606],
[-76.54520273208618, 39.17876344106642]
]
})
map.removeSource('some id'); // remove
Instance Members
Updates the image URL and, optionally, the coordinates. To avoid having
the image flash after changing,
set the raster-fade-duration
paint property on the raster
layer to 0.
updateImage(options: Object): ImageSource
Parameters
options
(Object)
Options object.
Name | Type | Description |
---|---|---|
options.url |
string?
|
Required image URL. |
options.coordinates |
Array<Array<number>>?
|
Four geographical coordinates, represented as arrays of longitude and latitude numbers, which define the corners of the image. The coordinates start at the top left corner of the image and proceed in clockwise order. They do not have to represent a rectangle. |
Returns
ImageSource
:
this
Sets the image's coordinates and re-renders the map.
setCoordinates(coordinates: Array<Array<number>>): ImageSource
Parameters
Returns
ImageSource
:
this
CanvasSource
A data source containing the contents of an HTML canvas. See CanvasSourceOptions for detailed documentation of options.
new CanvasSource(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented)
Extends ImageSource
Parameters
Example
// add to map
map.addSource('some id', {
type: 'canvas',
canvas: 'idOfMyHTMLCanvas',
animate: true,
coordinates: [
[-76.54, 39.18],
[-76.52, 39.18],
[-76.52, 39.17],
[-76.54, 39.17]
]
});
// update
var mySource = map.getSource('some id');
mySource.setCoordinates([
[-76.54335737228394, 39.18579907229748],
[-76.52803659439087, 39.1838364847587],
[-76.5295386314392, 39.17683392507606],
[-76.54520273208618, 39.17876344106642]
]);
map.removeSource('some id'); // remove
Instance Members
Enables animation. The image will be copied from the canvas to the map on each frame.
play()
Disables animation. The map will display a static copy of the canvas image.
pause()
Returns the HTML canvas
element.
getCanvas(): HTMLCanvasElement
Returns
HTMLCanvasElement
:
The HTML
canvas
element.
Sets the canvas's coordinates and re-renders the map.
setCoordinates(coordinates: Array<Array<number>>): CanvasSource
Parameters
Returns
CanvasSource
:
this
CanvasSourceOptions
Options to add a canvas source type to the map.
CanvasSourceOptions
Type: Object
Properties
canvas
((string | HTMLCanvasElement))
: Canvas source from which to read pixels. Can be a string representing the ID of
the canvas element, or the
HTMLCanvasElement
itself.
coordinates
(Array<Array<number>>)
: Four geographical coordinates denoting where to place the corners of the canvas,
specified in
[longitude, latitude]
pairs.
animate
(boolean?)
: Whether the canvas source is animated. If the canvas is static (i.e. pixels do not
need to be re-read on every frame),
animate
should be set to
false
to improve performance.
Events
Map
(and some other classes) emit events in response to user interactions or
changes in state. Evented
is the interface used to bind and unbind listeners for these events.
Evented
Methods mixed in to other classes for event capabilities.
Evented
Instance Members
Adds a listener to a specified event type.
on(type: string, listener: Function): Object
Parameters
type
(string)
The event type to add a listen 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
Object
:
this
Adds a listener that will be called only once to a specified event type.
The listener will be called first time the event fires after the listener is registered.
once(type: string, listener: Function): Object
Parameters
type
(string)
The event type to listen for.
listener
(Function)
The function to be called when the event is fired the first
time.
Returns
Object
:
this
MapMouseEvent
MapMouseEvent
is the event type for mouse-related map events.
new MapMouseEvent(type: string, map: Map, originalEvent: MouseEvent, data: Object)
Extends Object
Parameters
Example
// The `click` event is an example of a `MapMouseEvent`.
// Set up an event listener on the map.
map.on('click', function(e) {
// The event object (e) contains information like the
// coordinates of the point on the map that was clicked.
console.log('A click event has occurred at ' + e.lngLat);
});
Instance Members
The event type (one of Map.event:mousedown, Map.event:mouseup, Map.event:click, Map.event:dblclick, Map.event:mousemove, Map.event:mouseover, Map.event:mouseenter, Map.event:mouseleave, Map.event:mouseout, Map.event:contextmenu).
type
Type:
("mousedown"
| "mouseup"
|
"click"
| "dblclick"
|
"mousemove"
| "mouseover"
|
"mouseenter"
| "mouseleave"
|
"mouseout"
| "contextmenu"
)
The DOM event which caused the map event.
originalEvent
Type: MouseEvent
The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.
point
Type: Point
Prevents subsequent default processing of the event by the map.
Calling this method will prevent the following default map behaviors:
- On
mousedown
events, the behavior of DragPanHandler - On
mousedown
events, the behavior of DragRotateHandler - On
mousedown
events, the behavior of BoxZoomHandler - On
dblclick
events, the behavior of DoubleClickZoomHandler
preventDefault()
MapTouchEvent
MapTouchEvent
is the event type for touch-related map events.
new MapTouchEvent(type: string, map: Map, originalEvent: TouchEvent)
Extends Object
Parameters
Instance Members
The event type.
type
Type:
("touchstart"
| "touchend"
|
"touchcancel"
)
The DOM event which caused the map event.
originalEvent
Type: TouchEvent
The geographic location on the map of the center of the touch event points.
lngLat
Type: LngLat
The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left corner.
point
Type: Point
The array of pixel coordinates corresponding to a
touch
event's touches
property.
points
The geographical locations on the map corresponding to a
touch
event's touches
property.
lngLats
Prevents subsequent default processing of the event by the map.
Calling this method will prevent the following default map behaviors:
- On
touchstart
events, the behavior of DragPanHandler - On
touchstart
events, the behavior of TouchZoomRotateHandler
preventDefault()
MapBoxZoomEvent
A MapBoxZoomEvent
is the event type for the boxzoom-related map events
emitted by the BoxZoomHandler.
MapBoxZoomEvent
Type: Object
Properties
originalEvent
(MouseEvent)
: The DOM event that triggered the boxzoom event. Can be a
MouseEvent
or
KeyboardEvent
MapDataEvent
A MapDataEvent
object is emitted with the Map.event:data
and Map.event:dataloading events. Possible values
for
dataType
s are:
'source'
: The non-tile data associated with any source'style'
: The style used by the map
MapDataEvent
Type: Object
Properties
type
(string)
: The event type.
isSourceLoaded
(boolean?)
: True if the event has a
dataType
of
source
and the source has no outstanding network requests.
sourceDataType
(string?)
: Included if the event has a
dataType
of
source
and the event signals
that internal data has been received or changed. Possible values are
metadata
and
content
.
tile
(Object?)
: The tile being loaded or changed, if the event has a
dataType
of
source
and
the event is related to loading of a tile.
coord
(Coordinate?)
: The coordinate of the tile if the event has a
dataType
of
source
and
the event is related to loading of a tile.
Example
// The sourcedata event is an example of MapDataEvent.
// Set up an event listener on the map.
map.on('sourcedata', function(e) {
if (e.isSourceLoaded) {
// Do something when the source has finished loading
}
});
MapWheelEvent
MapWheelEvent
is the event type for the wheel
map event.
new MapWheelEvent(type: string, map: Map, originalEvent: WheelEvent)
Extends Object
Parameters
Instance Members
The event type.
type
Type:
"wheel"
The DOM event which caused the map event.
originalEvent
Type: WheelEvent
Prevents subsequent default processing of the event by the map.
Calling this method will prevent the the behavior of ScrollZoomHandler.
preventDefault()
Content Layers description
Content Layers
CustomRoad
Custom Road Content Layer
new CustomRoad(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): CustomRoad
Parameters
map
(Map)
The map.
Returns
CustomRoad
:
this
Remove the layer from a map.
remove(): CustomRoad
Returns
CustomRoad
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): CustomRoad
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
CustomRoad
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): CustomRoad
Returns
CustomRoad
:
this
Traffic
Traffic Content Layer
new Traffic(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
WeatherCloud
Weather Cloud Content Layer
new WeatherCloud(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): WeatherCloud
Parameters
map
(Map)
The map.
Returns
WeatherCloud
:
this
Remove the layer from a map.
remove(): WeatherCloud
Returns
WeatherCloud
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): WeatherCloud
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
WeatherCloud
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): WeatherCloud
Returns
WeatherCloud
:
this
WeatherRadar
Weather Radar Content Layer
new WeatherRadar(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): WeatherRadar
Parameters
map
(Map)
The map.
Returns
WeatherRadar
:
this
Remove the layer from a map.
remove(): WeatherRadar
Returns
WeatherRadar
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): WeatherRadar
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
WeatherRadar
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): WeatherRadar
Returns
WeatherRadar
:
this
WeatherAlert
Weather Alert Content Layer
new WeatherAlert(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): WeatherAlert
Parameters
map
(Map)
The map.
Returns
WeatherAlert
:
this
Remove the layer from a map.
remove(): WeatherAlert
Returns
WeatherAlert
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): WeatherAlert
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
WeatherAlert
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): WeatherAlert
Returns
WeatherAlert
:
this
WeatherAlertClickControl
The WeatherAlertClickControl
adds the ability to show a popup when a weather
alert is clicked on.
new WeatherAlertClickControl(options: Options?)
Extends ClickControlBase
Parameters
options
(Options?)
Example
const weatherAlertClickControl = TrimbleMaps.WeatherAlertClickControl();
map.addControl(weatherAlertClickControl);
WeatherAlertLegendControl
The WeatherAlertLegendControl
adds the ability to show a legend for the
weather alert layer. (Deprecated in v3.12. Use WeatherAlertFilterControl
.)
new WeatherAlertLegendControl(options: Options)
Parameters
options
(Options)
Example
var weatherAlertLegendControl = new TrimbleMaps.WeatherAlertLegendControl();
map.addControl(weatherAlertLegendControl, 'top-left');
WeatherAlertFilterControl
The WeatherAlertFilterControl
adds the ability to filter the weather alerts.
new WeatherAlertFilterControl(options: Object)
Extends FilterControlBase
Parameters
options
(Object)
Name | Type | Description |
---|---|---|
options.severity |
string
(default: 'All' )
|
Filters results based on the alert severity ("All", "Extreme", "Severe", "Moderate", "Minor", "Unknown"). |
options.urgency |
string
(default: 'All' )
|
Filters results based on the alert urgency ("All", "Immediate", "Expected", "Future", "Past", "Unknown"). |
options.certainty |
string
(default: 'All' )
|
Filters results based on the alert certainty ("All", "Observed", "Likely", "Possible", "Unlikely", "Unknown"). |
options.eventNames |
Array
|
Array of event names such as ["Winter Storm Warning", "Flood Watch"] . |
options.isVisible |
boolean
(default: true )
|
Controls the visibility of the selection controls. |
Example
const weatherAlertFilterControl = TrimbleMaps.WeatherAlertFilterControl();
map.addControl(weatherAlertFilterControl, 'top-left');
Instance Members
RoadSurface
Road Surface Content Layer
new RoadSurface(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): RoadSurface
Parameters
map
(Map)
The map.
Returns
RoadSurface
:
this
Remove the layer from a map.
remove(): RoadSurface
Returns
RoadSurface
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): RoadSurface
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
RoadSurface
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): RoadSurface
Returns
RoadSurface
:
this
TrafficCamera
Traffic Camera Content Layer
new TrafficCamera(options: Options)
Extends ContentBase
Parameters
options
(Options)
Instance Members
Add the layer to a map.
addTo(map: Map): TrafficCamera
Parameters
map
(Map)
The map.
Returns
TrafficCamera
:
this
Remove the layer from a map.
remove(): TrafficCamera
Returns
TrafficCamera
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): TrafficCamera
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
TrafficCamera
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): TrafficCamera
Returns
TrafficCamera
:
this
TrafficCameraClickControl
The TrafficCameraClickControl
adds the ability to show a popup when a
Traffic Camera Icon is clicked on.
new TrafficCameraClickControl(options: Options)
Extends ClickControlBase
Parameters
options
(Options)
Example
const trafficCameraClickControl = TrimbleMaps.TrafficCameraClickControl();
map.addControl(trafficCameraClickControl);
TrafficIncident
Traffic Incident Content Layer
new TrafficIncident(options: Options)
Extends ContentBase
Parameters
options
(Options)
Instance Members
Add the layer to a map.
addTo(map: Map): TrafficIncident
Parameters
map
(Map)
The map.
Returns
TrafficIncident
:
this
Remove the layer from a map.
remove(): TrafficIncident
Returns
TrafficIncident
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): TrafficIncident
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
TrafficIncident
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): TrafficIncident
Returns
TrafficIncident
:
this
TrafficIncidentClickControl
The TrafficIncidentClickControl
adds the ability to show a popup when a
Traffic Incident Icon is clicked on.
new TrafficIncidentClickControl(options: Options)
Extends ClickControlBase
Parameters
options
(Options)
Example
const trafficIncidentClickControl = TrimbleMaps.TrafficIncidentClickControl();
map.addControl(trafficIncidentClickControl);
TrafficIncidentFilterControl
The TrafficIncidentFilterControl
adds the ability to filter the traffic
incidents.
new TrafficIncidentFilterControl(options: Object)
Extends FilterControlBase
Parameters
options
(Object)
Name | Type | Description |
---|---|---|
options.incidentType |
string
(default: 'All' )
|
Filters results based on the incidentType ('All', 'incident', 'trafficjam', 'accident', 'weather', 'construction'). Default is 'All'. |
options.isVisible |
boolean
(default: true )
|
Controls the visiblity of the selection controls. |
Example
const trafficIncidentFilterControl = TrimbleMaps.TrafficIncidentFilterControl();
map.addControl(trafficIncidentFilterControl);
TruckRestriction
Truck Restriction Content Layer
new TruckRestriction(options: Options)
Extends ContentBase
Parameters
options
(Options)
Instance Members
Add the layer to a map.
addTo(map: Map): TruckRestriction
Parameters
map
(Map)
The map.
Returns
TruckRestriction
:
this
Remove the layer from a map.
remove(): TruckRestriction
Returns
TruckRestriction
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): TruckRestriction
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
TruckRestriction
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): TruckRestriction
Returns
TruckRestriction
:
this
TruckRestrictionClickControl
The TruckRestrictionClickControl
adds the ability to show a popup when a
Truck Restriction Icon is clicked on.
new TruckRestrictionClickControl(options: Options)
Extends ClickControlBase
Parameters
options
(Options)
Example
var truckRestrictionClickControl = TrimbleMaps.TruckRestrictionClickControl();
map.addControl(truckRestrictionClickControl);
TruckRestrictionFilterControl
The TruckRestrictionFilterControl
adds the ability to filter the truck
restrictions.
new TruckRestrictionFilterControl(options: Object)
Extends FilterControlBase
Parameters
options
(Object)
Name | Type | Description |
---|---|---|
options.category |
string
(default: 'All' )
|
Filters results based on the category ("All", "general", dimension", "hazmat", "multiple"). Default is 'All'. |
options.isVisible |
boolean
(default: true )
|
Controls the visiblity of the selection controls. |
options.vehicleOptions |
Object?
|
Vehicle options used to filter the visibility of restrictions. This helps to only display restrictions that are relevant to the vehicle. |
Example
var truckRestrictionFilterControl = TrimbleMaps.TruckRestrictionFilterControl();
map.addControl(truckRestrictionFilterControl);
PointsOfInterest
Points of Interest Content Layer
new PointsOfInterest(options: Options?)
Extends ContentBase
Parameters
options
(Options?)
Instance Members
Add the layer to a map.
addTo(map: Map): PointsOfInterest
Parameters
map
(Map)
The map.
Returns
PointsOfInterest
:
this
Remove the layer from a map.
remove(): PointsOfInterest
Returns
PointsOfInterest
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): PointsOfInterest
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
PointsOfInterest
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): PointsOfInterest
Returns
PointsOfInterest
:
this
Rail Service
Rail
Rail
Rail Service
Rail
Static Members
This API will generate the Lat/Lon route path.
postRoutePath
Parameters
Options
(RailRouteRequest)
Request options
Example
const request = TrimbleMaps.Rail.postRoutePath({
stops: [{
format: TrimbleMaps.Common.RailStationFormat.STATION_STATE,
name: 'Denver CO',
railroad: 'UP'
},
{
format: TrimbleMaps.Common.RailStationFormat.STATION_STATE,
name: 'Oakland CA',
railroad: 'UP'
}],
options: {
routingPreference: TrimbleMaps.Common.RailRoutePreference.PRACTICAL,
terminalSwitching: true,
amtrakRoutes: true,
intermodalOnlyStations: true,
distUnit: TrimbleMaps.Common.RailDistanceUnit.MILES
},
callback: function(error, response) {
if (error === null) {
console.log('success', response);
} else {
console.log('failure', error)
}
}
});
The API for locating rail freight station(s) by SPLC code in the database. Up to one station in an array will be returned in this release.
getStations
Parameters
Options
(RailStationRequest)
Request options
Example
const railStationLocation = TrimbleMaps.Rail.getStations({
splc: '344770000',
callback: function(error, response) {
if (error === null) {
console.log('success', response);
} else {
console.log('failure', error)
}
}
});
Misc
prewarm
Initializes resources like WebWorkers that can be shared across maps to lower load
times in some situations. TrimbleMaps.workerUrl
and
TrimbleMaps.workerCount
, if being
used, must be set before prewarm()
is called to have an effect.
By default, the lifecycle of these resources is managed automatically, and they are
lazily initialized when a Map is first created. By invoking prewarm()
,
these
resources will be created ahead of time, and will not be cleared when the last Map
is removed from the page. This allows them to be re-used by new Map instances that
are created later. They can be manually cleared by calling
TrimbleMaps.clearPrewarmedResources()
. This is only necessary if your web
page remains
active but stops using maps altogether.
This is primarily useful when using GL-JS maps in a single page app, wherein a user would navigate between various views that can cause Map instances to constantly be created and destroyed.
prewarm()
Example
TrimbleMaps.prewarm()
clearPrewarmedResources
Clears up resources that have previously been created by
TrimbleMaps.prewarm()
.
Note that this is typically not necessary. You should only call this function
if you expect the user of your app to not return to a Map view at any point
in your application.
clearPrewarmedResources()
Example
TrimbleMaps.clearPrewarmedResources()
APIKey
Gets and sets the JavaScript Maps SDK API key.
APIKey
Type: string
Returns
string
:
The API Key.
Example
TrimbleMaps.APIKey = "YOUR_KEY_HERE";
setAPIKey
Sets the API Key.
setAPIKey(key: string)
Parameters
key
(string)
The API Key.
APIToken
Gets and sets the token to be used for API calls. If set, this token will be used for all non-style related service calls (routing, geocoding, etc.).
APIToken
Type: string
Returns
string
:
The API Token.
Example
TrimbleMaps.APIToken = "YOUR_TOKEN_HERE";
setAPIToken
Sets the API Token. If set, this token will be used for all non-style related service calls (routing, geocoding, etc.).
setAPIToken(token: string)
Parameters
token
(string)
The API Token.
workerCount
Gets and sets the number of web workers instantiated on a page with GL JS maps. By default, it is set to half the number of CPU cores (capped at 6). Make sure to set this property before creating any map instances for it to have effect.
workerCount
Type: string
Returns
number
:
Number of workers currently configured.
Example
TrimbleMaps.workerCount = 2;
maxParallelImageRequests
Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, which affects performance in raster-heavy maps. 16 by default.
maxParallelImageRequests
Type: string
Returns
number
:
Number of parallel requests currently configured.
Example
TrimbleMaps.maxParallelImageRequests = 10;
clearStorage
Clears browser storage used by this library. Using this method flushes the tile cache that is managed by this library. Tiles may still be cached by the browser in some cases.
This API is supported on browsers where the Cache
API
is supported and enabled. This includes all major browsers when pages are served over
https://
, except Internet Explorer and Edge Mobile.
When called in unsupported browsers or environments (private or incognito mode), the callback will be called with an error argument.
clearStorage(callback: Function)
Parameters
callback
(Function)
Called with an error argument if there is an error.
Example
TrimbleMaps.clearStorage();
setRTLTextPlugin
Sets the map's RTL text plugin. Necessary for supporting languages like Arabic and Hebrew that are written right-to-left.
setRTLTextPlugin(pluginURL: string, callback: Function, lazy: boolean)
Parameters
pluginURL
(string)
URL pointing to the RTL text plugin source.
callback
(Function)
Called with an error argument if there is an error.
lazy
(boolean)
If set to
true
, will defer loading the plugin until rtl text is encountered,
rtl text will then be rendered only after the plugin finishes loading.
Example
TrimbleMaps.setRTLTextPlugin('');
getRTLTextPluginStatus
Gets the map's [RTL text plugin] status.
The status can be unavailable
(i.e. not requested or removed),
loading
, loaded
or error
.
If the status is loaded
and the plugin is requested again, an error will be
thrown.
getRTLTextPluginStatus()
Example
const pluginStatus = TrimbleMaps.getRTLTextPluginStatus();
EdgeInsets
An EdgeInset
object represents screen space padding applied to the edges of
the viewport.
This shifts the apprent center or the vanishing point of the map. This is useful for
adding floating UI elements
on top of the map and having the vanishing point shift as UI elements resize.
new EdgeInsets(top: number, bottom: number, left: number, right: number)
Parameters
Static Members
Interpolates the inset in-place.
This maintains the current inset value for any inset not present in
target
.
interpolate(start: (PaddingOptions | EdgeInsets), target: PaddingOptions, t: number): EdgeInsets
Parameters
Returns
EdgeInsets
:
edgeinsets
Returns the current sdtate as json, useful when you want to have a read-only representation of the inset.
toJSON(): PaddingOptions
Returns
PaddingOptions
:
JSON object
ContentBase
Content Layer Base Class
new ContentBase(options: Options)
Parameters
options
(Options)
Instance Members
Add the layer to a map.
addTo(map: any): any
Parameters
map
(any)
The map
Returns
any
:
this
Remove the layer from the map.
remove(): any
Returns
any
:
this
Set the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
setVisibility(isVisible: boolean): ContentBase
Parameters
isVisible
(boolean)
A boolean indicating the visibility of the layer.
Returns
ContentBase
:
this
Toggle the visibility of the layer. Visibility of layer content may be affected by other factors, such as zoom level.
toggleVisibility(): ContentBase
Returns
ContentBase
:
this
PlaceClickControl
The PlaceClickControl
adds the ability to show a popup when a Place Icon is
clicked on.
new PlaceClickControl(options: Options)
Extends ClickControlBase
Parameters
options
(Options)
Example
var placeClickControl = TrimbleMaps.PlaceClickControl();
map.addControl(placeClickControl);
StyleImageInterface
Interface for dynamically generated style images. This is a specification for implementers to model: it is not an exported method or class.
Images implementing this interface can be redrawn for every frame. They can be used to animate icons and patterns or make them respond to user input. Style images can implement a StyleImageInterface#render method. The method is called every frame and can be used to update the image.
StyleImageInterface
Properties
Example
var flashingSquare = {
width: 64,
height: 64,
data: new Uint8Array(64 * 64 * 4),
onAdd: function(map) {
this.map = map;
},
render: function() {
// keep repainting while the icon is on the map
this.map.triggerRepaint();
// alternate between black and white based on the time
var value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0;
// check if image needs to be changed
if (value !== this.previousValue) {
this.previousValue = value;
var bytesPerPixel = 4;
for (var x = 0; x < this.width; x++) {
for (var y = 0; y < this.height; y++) {
var offset = (y * this.width + x) * bytesPerPixel;
this.data[offset + 0] = value;
this.data[offset + 1] = value;
this.data[offset + 2] = value;
this.data[offset + 3] = 255;
}
}
// return true to indicate that the image changed
return true;
}
}
}
map.addImage('flashing_square', flashingSquare);
Instance Members
This method is called once before every frame where the icon will be
used.
The method can optionally update the image's data
member
with a new image.
If the method updates the image it must return true
to
commit the change.
If the method returns false
or nothing the image is assumed
to not have changed.
If updates are infrequent it maybe easier to use Map#updateImage to update the image instead of implementing this method.
render(): boolean
Returns
boolean
:
true
if this method updated the image.
false
if the image was not changed.
Optional method called when the layer has been added to the Map with Map#addImage.
onAdd(map: Map)
Parameters
map
(Map)
The Map this custom layer was just added to.
Optional method called when the icon is removed from the map with Map#removeImage. This gives the image a chance to clean up resources and event listeners.
onRemove()
VectorTileSource
A source containing vector tiles in [Mapbox Vector Tile format]. (See the [Style Specification] for detailed documentation of options.)
new VectorTileSource(id: string, options: any, dispatcher: Dispatcher, eventedParent: Evented)
Extends Evented
Parameters
Example
map.addSource('some id', {
type: 'vector',
tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],
minzoom: 6,
maxzoom: 14
});
map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);
Instance Members
Sets the source tiles
property and re-renders the map.
setTiles(tiles: Array<string>): VectorTileSource
Parameters
Returns
VectorTileSource
:
this
Sets the source url
property and re-renders the map.
setUrl(url: string): VectorTileSource
Parameters
Returns
VectorTileSource
:
this
MercatorCoordinate
A MercatorCoordinate
object represents a projected three dimensional
position.
MercatorCoordinate
uses the web mercator projection (EPSG:3857) with slightly different units:
- the size of 1 unit is the width of the projected world instead of the "mercator meter"
- the origin of the coordinate space is at the north-west corner instead of the middle
For example, MercatorCoordinate(0, 0, 0)
is the north-west corner of the
mercator world and
MercatorCoordinate(1, 1, 0)
is the south-east corner. If you are familiar
with
[vector tiles] the JavaScript Maps SDK it may be helpful to think
of the coordinate space as the 0/0/0
tile with an extent of 1
.
The z
dimension of MercatorCoordinate
is conformal. A cube in
the mercator coordinate space would be rendered as a cube.
new MercatorCoordinate(x: number, y: number, z: number)
Parameters
x
(number)
The x component of the position.
y
(number)
The y component of the position.
z
(number
= 0
)
The z component of the position.
Example
var nullIsland = new TrimbleMaps.MercatorCoordinate(0.5, 0.5, 0);
Static Members
Project a LngLat
to a MercatorCoordinate
.
fromLngLat(lngLatLike: LngLatLike, altitude: number): MercatorCoordinate
Parameters
lngLatLike
(LngLatLike)
The location to project.
altitude
(number
= 0
)
The altitude in meters of the position.
Returns
MercatorCoordinate
:
The projected mercator coordinate.
Example
var coord = TrimbleMaps.MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);
coord; // MercatorCoordinate(0.5, 0.5, 0)
Instance Members
Returns the distance of 1 meter in MercatorCoordinate
units
at this latitude.
For coordinates in real world units using meters, this naturally provides
the scale
to transform into MercatorCoordinate
s.
meterInMercatorCoordinateUnits(): number
Returns
number
:
Distance of 1 meter in
MercatorCoordinate
units.
Places
Places service
Places
Static Members
Gets authentication token for the api key.
authenticate
Returns
any
:
Promise
Example
const authPromise = TrimbleMaps.Places.authenticate();
authPromise.then((resp) => {
const token = JSON.parse(resp).token;
});
Gets the standard information about a single place.
getPlace
Parameters
Returns
any
:
Promise
Example
const placePromise = TrimbleMaps.Places.getPlace({
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
placeId: '0xlM0l28x0LEiCiOPrHt-_WQ'
});
Gets the full details about a single place.
getPlaceDetails
Parameters
Returns
any
:
Promise
Example
const placeDetailsPromise = TrimbleMaps.Places.getPlaceDetails({
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
placeId: '0xlM0l28x0LEiCiOPrHt-_WQ'
});
RoadSpeedBase
Represents a road speed based on road category. - service side type
RoadSpeedBase
Type: Object
Properties
roadCategory
(Common.RoadType)
speed
(number)
UndoRedoStack
The UndoRedoStack
object allows an app to track, undo or redo user actions.
The undo action has to start from the top and move to the bottom of the stack
sequentially.
The redo action has to start from the bottom and move to the top of the stack
sequentially.
Pushing a new item to the stack may remove undone items. For example, the stack has
total 5 item and 4 items have been undone.
If a new item is pushed in, the 4 undone items will be removed from the stack. The stack
will just have item 1 and the newly added one.
The assumption is that the current state is satisfying. There is no need to track
previous undone items after adding a new one.
You createa a UndoRedoStack
by specifying a baseline item.
new UndoRedoStack(options: Object, item: any)
Parameters
options
(Object)
item
(any)
Baseline item
Example
const undoRedoStack = new UndoRedoStack({
item: [...stops]
});
Instance Members
Pushes data item to a stack.
push(item: any)
Parameters
item
(any)
Data item
Example
undoRedoStack.push(stops);
Gets the data item that can be used to perform undo.
undo(): any
Returns
any
:
data item
Gets the data item that can be used to perform redo.
redo(): any
Returns
any
:
data item