Skip to main content

Map

Interactive map and support classes.

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 :
  • 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.
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
addControl(control, position?)
removeControl(control)
resize(eventData?)
getBounds()
getMaxBounds()
setMaxBounds(bounds)
setMinZoom(minZoom)
getMinZoom()
setMaxZoom(maxZoom)
getMaxZoom()
setMinPitch(minPitch)
getMinPitch()
setMaxPitch(maxPitch)
getMaxPitch()
getRenderWorldCopies()
setRenderWorldCopies(renderWorldCopies)
project(lnglat)
unproject(point)
isMoving()
isZooming()
isRotating()
on(type, layerId, listener)
once(type, listener)
once(type, layerId, listener)
off(type, listener)
off(type, layerId, listener)
queryRenderedFeatures(geometry?, options?)
querySourceFeatures(sourceId, parameters?)
setStyle(style, options?)
getStyle()
getStyleName()
setRegion(region)
getRegion()
isStyleLoaded()
addSource(id, source)
isSourceLoaded(id)
areTilesLoaded()
removeSource(id)
getSource(id)
addImage(id, image, options)
updateImage(id, image)
hasImage(id)
removeImage(id)
loadImage(url, callback)
listImages()
addLayer(layer, beforeId?)
moveLayer(id, beforeId?)
removeLayer(id)
getLayer(id)
setTrafficVisibility(isVisible)
isTrafficVisible()
toggleTrafficVisibility()
setWeatherRadarVisibility(isVisible)
isWeatherRadarVisible()
toggleWeatherRadarVisibility()
setWeatherCloudVisibility(isVisible)
isWeatherCloudVisible()
toggleWeatherCloudVisibility()
setWeatherAlertVisibility(isVisible)
isWeatherAlertVisible()
toggleWeatherAlertVisibility()
setRoadSurfaceVisibility(isVisible)
isRoadSurfaceVisible()
toggleRoadSurfaceVisibility()
setPOIVisibility(isVisible)
isPOIVisible()
togglePOIVisibility()
set3dBuildingVisibility(isVisible)
is3dBuildingVisible()
toggle3dBuildingVisibility()
setPlacesVisibility(isVisible)
isPlacesVisible()
togglePlacesVisibility()
setCustomRoadVisibility(isVisible)
isCustomRoadVisible()
toggleCustomRoadVisibility()
setLanguage(language)
setFilter(layerId, filter, options = {})
setLayerZoomRange(layerId, minzoom, maxzoom)
getFilter(layerId)
setPaintProperty(layerId, name, value, options = {})
getPaintProperty(layerId, name)
setLayoutProperty(layerId, name, value, options = {})
getLayoutProperty(layerId, name)
setLight(light, options = {})
getLight()
setFeatureState(feature, state)
removeFeatureState(target, key)
getFeatureState(feature)
getContainer()
getCanvasContainer()
getCanvas()
loaded()
remove()
triggerRepaint()
showTileBoundaries
showPadding
showCollisionBoxes
repaint
version
getCenter()
setCenter(center, eventData?)
panBy(offset, options?, eventData?)
panTo(lnglat, options?, eventData?)
getZoom()
setZoom(zoom, eventData?)
zoomTo(zoom, options, eventData?)
zoomIn(options?, eventData?)
zoomOut(options?, eventData?)
getBearing()
setBearing(bearing, eventData?)
getPadding()
setPadding(padding, eventData?)
rotateTo(bearing, options?, eventData?)
resetNorth(options?, eventData?)
resetNorthPitch(options?, eventData?)
snapToNorth(options?, eventData?)
getPitch()
setPitch(pitch, eventData?)
cameraForBounds(bounds, options?)
fitBounds(bounds, options?, eventData?)
fitScreenCoordinates(p0, p1, bearing, options?, eventData?)
jumpTo(options, eventData?)
easeTo(options, eventData?)
flyTo(options, eventData?)
stop()
Events
resize
remove
weatheralert.eventname
weatheralert.eventname
content.remove
content.remove
content.visibility
content.visibility
content.filter
content.filter
mousedown
mouseup
mouseover
mousemove
click
dblclick
mouseenter
mouseleave
mouseout
contextmenu
wheel
touchstart
touchend
touchmove
touchcancel
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
stylechanging
stylechange
customroadloading
customroadloading
customroad
customroad
trafficcameraloading
trafficcameraloading
trafficcamera
trafficcamera
trafficincidentloading
trafficincidentloading
trafficincident
trafficincident
truckrestrictionloading
truckrestrictionloading
truckrestriction
truckrestriction
weatherradarloading
weatherradarloading
weatherradar
weatherradar
weathercloudloading
weathercloudloading
weathercloud
weathercloud
weatheralertloading
weatheralertloading
weatheralert
weatheralert
trafficloading
trafficloading
traffic
traffic
roadsurfaceloading
roadsurfaceloading
roadsurface
roadsurface
pointsofinterestloading
pointsofinterestloading
pointsofinterest
pointsofinterest
visibility

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.
animate (boolean) : If false , no animation will occur.
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.
method (string) : Request method 'GET' | 'POST' | 'PUT' .
body (string) : Request body.
type (string) : Response body type to be returned 'string' | 'json' | 'arrayBuffer' .
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.
type (string) : The layer's type. Must be "custom" .
renderingMode (string) : Either "2d" or "3d" . Defaults to "2d" .
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
onAdd(map, gl)
onRemove(map, gl)
prerender(gl, matrix)
render(gl, matrix)

supported

Test whether the browser supports the JavaScript Maps SDK.

supported(options: Object?): boolean
Parameters
options (Object?)
Name Type Description
options.failIfMajorPerformanceCaveat boolean (default: false) If true , the function will return false if the performance of the JavaScript Maps SDK would be dramatically worse than expected (e.g. a software WebGL renderer would be used).
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

Enumerations for common property values.

Common

Common enumerations used across TrimbleMaps.

Common
Static Members
Style
Region
VehicleType
RouteType
RouteOptimization
ClassOverride
HazMatType
DistanceUnit
TruckUnit
FuelUnit
TruckConfig
TollCurrency
DataVersion
ReportType
TrailerType
EmissionType
RequestMethod
ETAETDType
DateOption
DayOfWeek
TimeZone
DataRegion
TollRoadsType
TunnelCategory
FuelType
SideOfStreetAdherenceLevel
HoSScheduleType
DisplayRestrictionsType
ZoneType
RoadType
RailStationFormat
RailRoutePreference
RailDistanceUnit
SnapMode
SnapKey
ViaPointModifierKey
SatelliteProvider

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
lng (number) Longitude, measured in degrees.
lat (number) Latitude, measured in degrees.
Example
  
    var ll = new TrimbleMaps.LngLat(-73.9749, 40.7736);
    
  
Static Members
convert(input)
Instance Members
wrap()
toArray()
toString()
distanceTo(lngLat)
toBounds(radius)

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
convert(input)
Instance Members
setNorthEast(ne)
setSouthWest(sw)
extend(obj)
getCenter()
getSouthWest()
getNorthEast()
getNorthWest()
getSouthEast()
getWest()
getSouth()
getEast()
getNorth()
toArray()
toString()
isEmpty()
contains(lnglat)

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

Type: (Point | Array<number>)

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 Layer

Route visualization.

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.
  • TrimbleMaps.Common.VehicleType.TRUCK - Truck
  • TrimbleMaps.Common.VehicleType.LIGHT_TRUCK - Light Truck
  • TrimbleMaps.Common.VehicleType.AUTOMOBILE - Automobile
options.routeType Common.RouteType? Default: TrimbleMaps.Common.RouteType.PRACTICAL
Type of route.
  • TrimbleMaps.Common.RouteType.PRACTICAL - Practical
  • TrimbleMaps.Common.RouteType.SHORTEST - Shortest
  • TrimbleMaps.Common.RouteType.FASTEST - Fastest
options.routeOptimization Common.RouteOptimization? Default: TrimbleMaps.Common.RouteOptimization.NONE
  • TrimbleMaps.Common.RouteOptimization.NONE - None
  • TrimbleMaps.Common.RouteOptimization.OPTIMIZE_ALL_STOPS - Optimize all stops
  • TrimbleMaps.Common.RouteOptimization.OPTIMIZE_INTERMEDIATE_STOPS - Optimize intermediate stops
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.
  • TrimbleMaps.Common.HazMatType.NONE - None
  • TrimbleMaps.Common.HazMatType.GENERAL - General
  • TrimbleMaps.Common.HazMatType.CAUSTIC - Caustic
  • TrimbleMaps.Common.HazMatType.EXPLOSIVES - Explosives
  • TrimbleMaps.Common.HazMatType.FLAMMABLE - Flammable
  • TrimbleMaps.Common.HazMatType.INHALANTS - Inhalants
  • TrimbleMaps.Common.HazMatType.RADIOACTIVE - Radioactive
  • TrimbleMaps.Common.HazMatType.HARMFUL_TO_WATER - HarmfulToWater
  • TrimbleMaps.Common.HazMatType.TUNNEL - Tunnel

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.
  • TrimbleMaps.Common.DistanceUnit.MILES - Miles
  • TrimbleMaps.Common.DistanceUnit.KILOMETERS - 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.
  • TrimbleMaps.Common.TruckUnit.ENGLISH - English
  • TrimbleMaps.Common.TruckUnit.METRIC - 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.
  • TrimbleMaps.Common.FuelUnit.GALLONS - Gallons
  • TrimbleMaps.Common.FuelUnit.LITERS - Liters
options.truckConfig Common.TruckConfig? Default: TrimbleMaps.Common.TruckConfig.NONE
The vehicle style.
  • TrimbleMaps.Common.TruckConfig.NONE - Indicates that no particular vehicle style is chosen.
  • TrimbleMaps.Common.TruckConfig.TWENTY_EIGHT - 28' double trailer.
  • TrimbleMaps.Common.TruckConfig.FORTY - 40' straight trailer.
  • TrimbleMaps.Common.TruckConfig.FORTY_EIGHT - 48' semitrailer.
  • TrimbleMaps.Common.TruckConfig.FIFTY_THREE - 53' semitrailer.
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.
  • TrimbleMaps.Common.Region.AF - Africa
  • TrimbleMaps.Common.Region.AS - Asia
  • TrimbleMaps.Common.Region.EU - Europe
  • TrimbleMaps.Common.Region.ME - Middle East
  • TrimbleMaps.Common.Region.NA - North America
  • TrimbleMaps.Common.Region.OC - Australia
  • TrimbleMaps.Common.Region.SA - South America
  • TrimbleMaps.Common.Region.WW - Worldwide
options.dataVersion Common.DataVersion?
options.reportType Array? Default: [TrimbleMaps.Common.ReportType.MILEAGE]
The data region in which the route stops are located.
  • TrimbleMaps.Common.ReportType.MILEAGE - Mileage
  • TrimbleMaps.Common.ReportType.DIRECTIONS - Directions
  • TrimbleMaps.Common.ReportType.DETAIL - Detail
  • TrimbleMaps.Common.ReportType.STATE - State
  • TrimbleMaps.Common.ReportType.TOLL - Toll Detail
  • TrimbleMaps.Common.ReportType.ROAD - Road Type
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.
  • TrimbleMaps.Common.TrailerType.NONE - None
  • TrimbleMaps.Common.TrailerType.CARAVAN - Caravan
  • TrimbleMaps.Common.TrailerType.TRAILER - Trailer
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.
  • TrimbleMaps.Common.EmissionType.EURO0 - Euro0
  • TrimbleMaps.Common.EmissionType.EUROI - EuroI
  • TrimbleMaps.Common.EmissionType.EUROII - EuroII
  • TrimbleMaps.Common.EmissionType.EUROIII - EuroIII
  • TrimbleMaps.Common.EmissionType.EUROIV - EuroIV
  • TrimbleMaps.Common.EmissionType.EUROV - EuroV
  • TrimbleMaps.Common.EmissionType.EUROVI EuroVI
  • TrimbleMaps.Common.EmissionType.EUROEEV - EuroEEV
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.
  • TrimbleMaps.Common.ClassOverride.NONE - No class overrides
  • TrimbleMaps.Common.ClassOverride.FIFTY_THREE - 53' class override
  • TrimbleMaps.Common.ClassOverride.NATIONAL_NETWORK - National Network class override
  • TrimbleMaps.Common.ClassOverride.ALL - 53' and National Network class override
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
setVisibility(isVisible)
isVisible()
toggleVisibility()
addTo(map)
getBottomLayerId()
moveLayer(beforeId?)
remove()
update(options)
frameRoute()
frame()
getRouteId()
getReports(options)
styleStopIcons(style)
addStopIcon(stopType, url)
getRouteWithNewStop(newStop, routeLegPosition)
canUndo()
canRedo()
undo()
redo()
_updateStopsThenGetRoute(stops)
enableRouteStack()
disableRouteStack()
setDraggable(isDraggable)
Events
routeloading
route
mouseenter
mouseleave
click
stopInserting
reportloading
report

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
size (number)
spacing (number)
fillColor (string)
fillOpacity (number)
strokeColor (string)
strokeWidth (number)
strokeOpacity (number)

DragRouteOptions

DragRouteOptions

Type: Object

Properties
snapMode (Common.SnapMode)
snapKey (Common.SnapKey)
viaPointModifierKey (Common.ViaPointModifierKey)

Services

Helper classes to access web services.

Geocoder

Geocoder

Geocoder
Static Members
geocode
reverseGeocode

Search

Search
Static Members
singleSearch

Routing

Routing

Routing
Static Members
postDerivedRoutePath
postDerivedRouteReports
postRoadSurfaceRoute

User Interface

Controls, markers, and popups add new user interface elements to the map.

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
onAdd(map)
onRemove(map)
getDefaultPosition()

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
trigger()
Events
geolocate
error
outofmaxbounds
trackuserlocationstart
trackuserlocationend

AttributionControl

An AttributionControl control presents the map's attribution information.

new AttributionControl(options: Object?)
Parameters
options (Object? = {})
Name Type Description
options.compact boolean? If true force a compact attribution that shows the full attribution on mouse hover, or if false force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide.
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
options (Object?)
Name Type Description
options.maxWidth number (default: '100') The maximum length of the scale control in pixels.
options.unit string (default: 'metric') Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).
Example
  
    var scale = new TrimbleMaps.ScaleControl({
    maxWidth: 80,
    unit: 'imperial'
});
map.addControl(scale);
scale.setUnit('metric');
    
  
Instance Members
setUnit(unit)

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());
    
  

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:
  • a single number specifying a distance from the popup's location
  • a PointLike specifying a constant offset
  • an object of Points specifing an offset for each anchor position Negative offsets indicate left and up.
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
addTo(map)
isOpen()
remove()
getLngLat()
setLngLat(lnglat)
trackPointer()
getElement()
setText(text)
setHTML(html)
getMaxWidth()
setMaxWidth(maxWidth)
setDOMContent(htmlNode)
addClassName(className)
removeClassName(className)
toggleClassName(className)
Events
open
close

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
addTo(map)
remove()
getLngLat()
setLngLat(lnglat)
getElement()
setPopup(popup)
getPopup()
togglePopup()
getOffset()
setOffset(offset)
setDraggable(shouldBeDraggable)
isDraggable()
setRotation(rotation)
getRotation()
setRotationAlignment(alignment)
getRotationAlignment()
setPitchAlignment(alignment?)
getPitchAlignment()
Events
dragstart
drag
dragend

User Interaction Handlers

Handlers add different kinds of interactivity to the map - mouse interactivity, touch interactions, and other gestures.

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
map (Map)
options ({clickTolerance: number})
Instance Members
isEnabled()
isActive()
enable()
disable()

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
setZoomRate(zoomRate)
setWheelZoomRate(wheelZoomRate)
isEnabled()
enable(options?)
disable()

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
mousePan (MousePanHandler)
touchPan (TouchPanHandler)
Instance Members
enable(options?)
disable()
isEnabled()
isActive()

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
options (Object?)
mouseRotate (MouseRotateHandler)
mousePitch (MousePitchHandler)
Instance Members
enable()
disable()
isEnabled()
isActive()

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
enable()
disable()
isEnabled()
isActive()

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
touchZoom (TouchZoomHandler)
touchRotate (TouchRotateHandler)
tapDragZoom (TapDragZoomHandler)
Instance Members
enable(options?)
disable()
isEnabled()
isActive()
disableRotation()
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
isEnabled
isActive
enable
disable

Sources

Sources specify the geographic features to be rendered on the map. Source objects may be obtained from Map#getSource.

GeoJSONSource

A source containing GeoJSON.

new GeoJSONSource(id: string, options: any, dispatcher: Dispatcher, eventedParent: Evented)

Extends Evented

Parameters
id (string)
options (any)
dispatcher (Dispatcher)
eventedParent (Evented)
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
setData(data)
getClusterExpansionZoom(clusterId, callback)
getClusterChildren(clusterId, callback)
getClusterLeaves(clusterId, limit, offset, callback)

VideoSource

A data source containing video.

new VideoSource(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented)

Extends ImageSource

Parameters
id (string)
options (VideoSourceSpecification)
dispatcher (Dispatcher)
eventedParent (Evented)
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
pause()
play()
getVideo()
setCoordinates()

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
updateImage(options)
setCoordinates(coordinates)

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
id (string)
options (CanvasSourceSpecification)
dispatcher (Dispatcher)
eventedParent (Evented)
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
play()
pause()
getCanvas()
setCoordinates(coordinates)

CanvasSourceOptions

Options to add a canvas source type to the map.

CanvasSourceOptions

Type: Object

Properties
type (string) : Source type. Must be "canvas" .
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
on(type, listener)
off(type, listener)
once(type, listener)

MapMouseEvent

MapMouseEvent is the event type for mouse-related map events.

new MapMouseEvent(type: string, map: Map, originalEvent: MouseEvent, data: Object)

Extends Object

Parameters
type (string)
map (Map)
originalEvent (MouseEvent)
data (Object = {})
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
type
target
originalEvent
point
lngLat
preventDefault()
defaultPrevented

MapTouchEvent

MapTouchEvent is the event type for touch-related map events.

new MapTouchEvent(type: string, map: Map, originalEvent: TouchEvent)

Extends Object

Parameters
type (string)
map (Map)
originalEvent (TouchEvent)
Instance Members
type
target
originalEvent
lngLat
point
points
lngLats
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
type (string) : The type of boxzoom event. One of boxzoomstart , boxzoomend or boxzoomcancel
target (Map) : The Map instance that triggerred the event

MapDataEvent

A MapDataEvent object is emitted with the Map.event:data and Map.event:dataloading events. Possible values for dataTypes 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.
dataType (string) : The type of data that has changed. One of 'source' , 'style' .
isSourceLoaded (boolean?) : True if the event has a dataType of source and the source has no outstanding network requests.
source (Object?) : The style spec if the event has a dataType of source .
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
type (string)
map (Map)
originalEvent (WheelEvent)
Instance Members
type
target
originalEvent
preventDefault()

Content Layers

Content Layers description

CustomRoad

Custom Road Content Layer

new CustomRoad(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

Traffic

Traffic Content Layer

new Traffic(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

WeatherCloud

Weather Cloud Content Layer

new WeatherCloud(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

WeatherRadar

Weather Radar Content Layer

new WeatherRadar(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

WeatherAlert

Weather Alert Content Layer

new WeatherAlert(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

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
getFilter()

RoadSurface

Road Surface Content Layer

new RoadSurface(options: Options?)

Extends ContentBase

Parameters
options (Options?)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

TrafficCamera

Traffic Camera Content Layer

new TrafficCamera(options: Options)

Extends ContentBase

Parameters
options (Options)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

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
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

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
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

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
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

Rail

Rail Service

Rail

Rail Service

Rail
Static Members
postRoutePath
getStations

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
top (number = 0)
bottom (number = 0)
left (number = 0)
right (number = 0)
Static Members
interpolate(start, target, t)
getCenter(width, height)
toJSON()

ContentBase

Content Layer Base Class

new ContentBase(options: Options)
Parameters
options (Options)
Instance Members
addTo(map)
remove()
isVisible()
setVisibility(isVisible)
toggleVisibility()

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
width (number)
height (number)
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
render()
onAdd(map)
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
id (string)
options (any)
dispatcher (Dispatcher)
eventedParent (Evented)
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
setTiles(tiles)
setUrl(url)

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
fromLngLat(lngLatLike, altitude)
Instance Members
toLngLat()
toAltitude()
meterInMercatorCoordinateUnits()

Places

Places service

Places
Static Members
authenticate
getPlace
getPlaceDetails

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
push(item)
size()
canUndo()
canRedo()
undo()
redo()