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 Trimble Maps 2.0 JS API 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 Trimble Maps 2.0 JS API 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.style (Object | string | Common.Style)? The map's style.
options.region Common.Region? The map's region.
options.hash boolean (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 .
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.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 (default true) If true , the "drag to pan" interaction is enabled (see DragPanHandler ).
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.trackResize boolean (default true) If true , the map will automatically resize when the browser window resizes.
options.center LngLatLike (default [0,0]) The inital geographical centerpoint of the map. If center is not specified in the constructor options, Trimble Maps 2.0 JS API 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: Trimble Maps 2.0 JS API 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, Trimble Maps 2.0 JS API 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, Trimble Maps 2.0 JS API 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, Trimble Maps 2.0 JS API 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.renderWorldCopies boolean (default true) If true , multiple copies of the world will be rendered, when zoomed out.
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 null) If specified, defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs' 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). 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.
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)
getRenderWorldCopies()
setRenderWorldCopies(renderWorldCopies)
getMaxZoom()
project(lnglat)
unproject(point)
isMoving()
isZooming()
isRotating()
on(type, listener)
on(type, layer, listener)
off(type, listener)
off(type, layer, listener)
queryRenderedFeatures(geometry?, options?)
querySourceFeatures(sourceID, parameters?)
setStyle(style, options?)
getStyle()
setRegion(region)
getRegion()
isStyleLoaded()
addSource(id, source)
isSourceLoaded(id)
areTilesLoaded()
removeSource(id)
getSource(id)
addImage(id, image, options)
hasImage(id)
removeImage(id)
loadImage(url, callback)
listImages()
addLayer(layer, before?)
moveLayer(id, beforeId?)
removeLayer(id)
getLayer(id)
setFilter(layer, filter)
setLayerZoomRange(layerId, minzoom, maxzoom)
getFilter(layer)
setPaintProperty(layer, name, value)
getPaintProperty(layer, name)
setLayoutProperty(layer, name, value)
getLayoutProperty(layer, name)
setLight(light)
getLight()
setFeatureState(feature, state)
getFeatureState(feature)
getContainer()
getCanvasContainer()
getCanvas()
loaded()
remove()
triggerRepaint()
showTileBoundaries
showCollisionBoxes
repaint
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?)
rotateTo(bearing, options?, eventData?)
resetNorth(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
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
error
data
styledata
sourcedata
dataloading
styledataloading
sourcedataloading

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.

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, a bearing of 90° orients the map so that east is up.
pitch (number) : The desired pitch, in degrees.
around (LngLatLike) : If zoom is specified, around determines the point around which the zoom is centered.

PaddingOptions

Options for setting padding on a call to Map#fitBounds. 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.

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.
credentials (string) : 'same-origin'|'include' Use 'include' to send cookies with 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.

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
onRemove(map)
render(gl, matrix)
onAdd(map, gl)
prerender(gl, matrix)

supported

Test whether the browser supports Trimble Maps 2.0 JS API.

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 Trimble Maps 2.0 JS API 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 Trimble Maps 2.0 JS API 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
TollCurrency
DataVersion
ReportType

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.

Trimble Maps 2.0 JS API uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.

Note that any Trimble Maps 2.0 JS API 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()
toBounds(radius)

LngLatLike

A LngLat object, an array of two numbers representing longitude and latitude, or an object with lng and lat properties.

LngLatLike

Type: (LngLat | {lng: number, lat: number} | [number, number])

Example
  
    var v1 = new TrimbleMaps.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 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 Trimble Maps 2.0 JS API 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()

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

PointLike

A Point or an array of two numbers representing x and y screen coordinates in pixels.

PointLike

Type: (Point | Array<number>)

Geocoding

The Geocoding service provides methods related to converting street addresses to/from longitude and latitude coordinates.

Geocoder

Geocoder

Geocoder
Static Members
geocode
reverseGeocode

Routing

Routing layer

Route

Creates a route component

new Route(options: RouteOptions)

Extends Evented

Parameters
options (RouteOptions)
Name Type Description
options.routeId string? Unique
options.stops Array? Array of stops
options.vehicleType Common.VehicleType?
options.routeType Common.RouteType?
options.routeOptimization Common.RouteOptimization?
options.tollDiscourage number?
options.bordersOpen number?
options.overrideRestrict number?
options.highwayOnly number?
options.hazMatType Common.HazMatType?
options.distanceUnits Common.DistanceUnit?
options.trkUnits Common.TruckUnit?
options.trkHeight number?
options.trkLength number?
options.trkWidth number?
options.trkWeight number?
options.trkAxles number?
options.inclFerryDist number?
options.fuelUnits Common.FuelUnit?
options.truckConfig Common.TruckConfig?
options.inclTollData number?
options.fuelEconLoad number?
options.fuelEconEmpty number?
options.costPerFuelUnit number?
options.costGHG number?
options.costMaintLoad number?
options.costMaintEmpty number?
options.costTimeLoad number?
options.costTimeEmpty number?
options.tollCurrency Common.TollCurrency?
options.exchangeRate number?
options.citeInt number?
options.region Common.Region?
options.dataVersion Common.DataVersion?
options.reportType Array?
Example
  
    var route = new TrimbleMaps.Route({
    routeId: 'myRoute',
    stops: [
        new TrimbleMaps.LngLat(-74.566234, 40.499440),
        new TrimbleMaps.LngLat(-74.629749, 40.261187)
    ],
    routeType: TrimbleMaps.Common.RouteType.SHORTEST
  })
  .addTo(map);
    
  
Instance Members
addTo(map)
remove()
update(options)
frameRoute()
getRouteId()
getReports(options)

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 an 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 Trimble Maps 2.0 JS API'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
getDefaultPosition()
onAdd(map)
onRemove(map)

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.
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 not be visible.

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 states:

  • active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center.
  • passive - the user's location dot automatically updates, but the map's camera does not.
  • disabled
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 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.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
trackuserlocationend
geolocate
error
trackuserlocationstart

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()
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.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 specifying 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
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>")
  .addTo(map);
    
  
Instance Members
addTo(map)
isOpen()
remove()
getLngLat()
setLngLat(lnglat)
setText(text)
setHTML(html)
setDOMContent(htmlNode)
Events
open
close

Marker

Creates a marker component

new Marker(options: Object?)

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.draggable boolean (default false) A boolean indicating whether or not a marker is able to be dragged to a new position on the map.
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()
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)
Parameters
map (Map)
Instance Members
isEnabled()
enable(options?)
disable()

DragPanHandler

The DragPanHandler allows the user to pan the map by clicking and dragging the cursor.

new DragPanHandler(map: Map, options: {clickTolerance: number?})
Parameters
map (Map)
options ({clickTolerance: number?})
Instance Members
isEnabled()
isActive()
enable()
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(map: Map, options: Object?)
Parameters
map (Map) The Trimble Maps 2.0 JS API map to add the handler to.
options (Object?)
Instance Members
isEnabled()
isActive()
enable()
disable()

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(map: Map)
Parameters
map (Map)
Instance Members
isEnabled()
enable()
disable()

DoubleClickZoomHandler

The DoubleClickZoomHandler allows the user to zoom the map at a point by double clicking or double tapping.

new DoubleClickZoomHandler(map: Map)
Parameters
map (Map)
Instance Members
isEnabled()
isActive()
enable()
disable()

TouchZoomRotateHandler

The TouchZoomRotateHandler allows the user to zoom and rotate the map by pinching on a touchscreen.

new TouchZoomRotateHandler(map: Map)
Parameters
map (Map)
Instance Members
isEnabled()
enable(options?)
disable()
disableRotation()
enableRotation()

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

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
pause()
play()
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 = {})
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()
defaultPrevented

MapBoxZoomEvent

MapBoxZoomEvent

Type: Object

Properties
originalEvent (MouseEvent)
boxZoomBounds (LngLatBounds) : The bounding box of the "box zoom" interaction. This property is only provided for boxzoomend events.

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.

APIKey

Gets and sets the Trimble Maps 2.0 JS API key.

APIKey

Type: string

Example
  
    TrimbleMaps.APIKey = "YOUR_KEY_HERE";
    
  

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)
Parameters
pluginURL (string) URL pointing to the RTL text plugin source.
callback (Function) Called with an error argument if there is an error.
Example
  
    TrimbleMaps.setRTLTextPlugin('');
    
  

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