Skip to content

Markers and controls


User interface elements that can be added to the map. The items in this section exist outside of the map's canvas element.

Marker

src/ui/marker.ts Creates a marker component

Extends Evented.

new Marker(options: Object?, legacyOptions: MarkerOptions?)

Parameters

options(Object?)

Name Description
options.elementHTMLElement? DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
options.anchorstringdefault: '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.offsetPointLike? The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.
options.colorstringdefault: '#3FB1CE' The color to use for the default marker if options.element is not provided. The default is light blue.
options.scalenumberdefault: 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.draggablebooleandefault: false A boolean indicating whether or not a marker is able to be dragged to a new position on the map.
options.clickTolerancenumberdefault: 0 The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's clickTolerance.
options.rotationnumberdefault: 0 The rotation angle of the marker in degrees, relative to its respective rotationAlignment setting. A positive value will rotate the marker clockwise.
options.pitchAlignmentstringdefault: '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.rotationAlignmentstringdefault: '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 .

Example

var marker = new vietmapgl.Marker()
    .setLngLat([30.5, 50.5])
    .addTo(map);


// Set options
var marker = new vietmapgl.Marker({
    color: "#FFFFFF",
    draggable: true
    }).setLngLat([30.5, 50.5])
.addTo(map);

Instance Members

addTo(map)

Attaches the Marker to a Map object.

Parameters

map(Map)The vietmap GL JS map to add the marker to.

Returns

Marker: this

Example

var marker = new vietmapgl.Marker()
.setLngLat([30.5, 50.5])
.addTo(map); // add the marker to the map

getElement()

Returns the Marker's HTML element.

Returns

HTMLElement: element

getLngLat()

Get the marker's geographical location.

The longitude of the result may differ by a multiple of 360 degrees from the longitude previously set by setLngLat because Marker wraps the anchor longitude across copies of the world to keep the marker on screen.

Returns

LngLat: A LngLat describing the marker's location.

Example

// Store the marker's longitude and latitude coordinates in a variable
var lngLat = marker.getLngLat();
// Print the marker's longitude and latitude values in the console
console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )

Related

  • Create a draggable Marker

getOffset()

Get the marker's offset.

Returns

Point: The marker's screen coordinates in pixels.

getPitchAlignment()

Returns the current pitchAlignment property of the marker.

Returns

string: The current pitch alignment of the marker in degrees.

getPopup()

Returns the Popup instance that is bound to the Marker.

Returns

Popup: popup

Example

var marker = new vietmapgl.Marker()
.setLngLat([0, 0])
.setPopup(new vietmapgl.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);

console.log(marker.getPopup()); // return the popup instance

getRotation()

Returns the current rotation angle of the marker (in degrees).

Returns

number: The current rotation angle of the marker.

getRotationAlignment()

Returns the current rotationAlignment property of the marker.

Returns

string: The current rotational alignment of the marker.

isDraggable()

Returns true if the marker can be dragged

Returns

boolean: True if the marker is draggable.

remove()

Removes the marker from a map

Returns

Marker: this

Example

var marker = new vietmapgl.Marker().addTo(map);
marker.remove();

setDraggable(shouldBeDraggable)

Sets the draggable property and functionality of the marker

Parameters

shouldBeDraggable(boolean)(default false)Turns drag functionality on/off

Returns

Marker: this

setLngLat(lnglat)

Set the marker's geographical position and move it.

Parameters

lnglat(LngLat)A LngLat describing where the marker should be located.

Returns

Marker: this

Example

// Create a new marker, set the longitude and latitude, and add it to the map
new vietmapgl.Marker()
.setLngLat([-65.017, -16.457])
.addTo(map);

Related

  • Add custom icons with Markers

  • Create a draggable Marker

setOffset(offset)

Sets the offset of the marker

Parameters

offset(PointLike)The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.

Returns

Marker: this

setPitchAlignment(alignment?)

Sets the pitchAlignment property of the marker.

Parameters

alignment(string?)Sets the pitchAlignment property of the marker. If alignment is 'auto', it will automatically match rotationAlignment .

Returns

Marker: this

setPopup(popup?)

Binds a Popup to the Marker.

Parameters

popup((Popup | null)?)An instance of the Popup class. If undefined or null, any popup set on this Marker instance is unset.

Returns

Marker: this

Example

var marker = new vietmapgl.Marker()
.setLngLat([0, 0])
.setPopup(new vietmapgl.Popup().setHTML("<h1>Hello World!</h1>")) // add popup
.addTo(map);

Related

Attach a popup to a marker instance

setRotation(rotation)

Sets the rotation property of the marker.

Parameters

rotation(number)(default 0)The rotation angle of the marker (clockwise, in degrees), relative to its respective Marker#setRotationAlignment setting.

Returns

Marker: this

setRotationAlignment(alignment)

Sets the rotationAlignment property of the marker.

Parameters

alignment(string)(default 'auto')Sets the rotationAlignment property of the marker.

Returns

Marker: this

togglePopup()

Opens or closes the Popup instance that is bound to the Marker, depending on the current state of the Popup.

Returns

Marker: this

Example

var marker = new vietmapgl.Marker()
.setLngLat([0, 0])
.setPopup(new vietmapgl.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);

marker.togglePopup(); // toggle popup open or closed

Events

drag

Fired while dragging

Properties

marker(Marker): object that is being dragged

dragend

Fired when the marker is finished being dragged

Properties

marker(Marker): object that was dragged

dragstart

Fired when dragging starts

Properties

marker(Marker): object that is being dragged

Related

  • Add custom icons with Markers

  • Create a draggable Marker

Popup

src/ui/popup.ts

A popup component.

Extends Evented.

new Popup(options: Object?)

Parameters

options(Object?)

Name Description
options.closeButtonbooleandefault: true
options.closeOnClickbooleandefault: true If true , the popup will closed when the map is clicked.
options.closeOnMovebooleandefault: false If true , the popup will closed when the map moves.
options.focusAfterOpenbooleandefault: true If true , the popup will try to focus the first focusable element inside the popup.
options.anchorstring? 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
options.classNamestring? Space-separated CSS class names to add to popup container
options.maxWidthstringdefault: '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 vietmapgl.Popup({offset: popupOffsets, className: 'my-class'})
.setLngLat(e.lngLat)
.setHTML("<h1>Hello World!</h1>")
.setMaxWidth("300px")
.addTo(map);

Instance Members

addclassName(className)

Adds a CSS class to the popup container element.

Parameters

className(string)Non-empty string with CSS class name to add to popup container

Example

let popup = new vietmapgl.Popup()
popup.addClassName('some-class')

addTo(map)

Adds the popup to a map.

Parameters

map(Map)The vietmap GL JS map to add the popup to.

Returns

Popup: this

Example

new vietmapgl.Popup()
.setLngLat([0, 0])
.setHTML("<h1>Null Island</h1>")
.addTo(map);

Related

  • Display a popup

  • Display a popup on hover

  • Display a popup on click

  • Show polygon information on click

getElement()

Returns the Popup's HTML element.

Returns

HTMLElement: element

Example

// Change the `Popup` element's font size
var popup = new vietmapgl.Popup()
.setLngLat([-96, 37.8])
.setHTML("<p>Hello World!</p>")
.addTo(map);
var popupElem = popup.getElement();
popupElem.style.fontSize = "25px";

getLngLat()

Returns the geographical location of the popup's anchor.

The longitude of the result may differ by a multiple of 360 degrees from the longitude previously set by setLngLat because Popup wraps the anchor longitude across copies of the world to keep the popup on screen.

Returns

LngLat: The geographical location of the popup's anchor.

getMaxWidth()

Returns the popup's maximum width.

Returns

string: The maximum width of the popup.

isOpen()

Returns

boolean: true if the popup is open, false if it is closed.

remove()

Removes the popup from the map it has been added to.

Returns

Popup: this

Example

var popup = new vietmapgl.Popup().addTo(map);
popup.remove();

removeClassName(className)

Removes a CSS class from the popup container element.

Parameters

className(string)Non-empty string with CSS class name to remove from popup container

Example

let popup = new vietmapgl.Popup()
popup.removeClassName('some-class')

setDOMContent(htmlNode)

Sets the popup's content to the element provided as a DOM node.

Parameters

htmlNode(Node)A DOM node to be used as content for the popup.

Returns

Popup: this

Example

// create an element with the popup content
var div = document.createElement('div');
div.innerHTML = 'Hello, world!';
var popup = new vietmapgl.Popup()
.setLngLat(e.lngLat)
.setDOMContent(div)
.addTo(map);

setHTML(html)

Sets the popup's content to the HTML provided as a string.

This method does not perform HTML filtering or sanitization, and must be used only with trusted content. Consider Popup#setText if the content is an untrusted text string.

Parameters

html(string)A string representing HTML content for the popup.

Returns

Popup: this

Example

var popup = new vietmapgl.Popup()
.setLngLat(e.lngLat)
.setHTML("<h1>Hello World!</h1>")
.addTo(map);

Related

  • Display a popup

  • Display a popup on hover

  • Display a popup on click

  • Attach a popup to a marker instance

setLngLat(lnglat)

Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.

Parameters

lnglat(LngLatLike)The geographical location to set as the popup's anchor.

Returns

Popup: this

setMaxWidth(maxWidth)

Sets the popup's maximum width. This is setting the CSS property max-width. Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width

Parameters

maxWidth(string)A string representing the value for the maximum width.

Returns

Popup: this

setOffset(offset?)

Sets the popup's offset.

Parameters

offset(Offset?)Sets the popup's offset.

Returns

Popup: this

setText(text)

Sets the popup's content to a string of text.

This function creates a Text node in the DOM, so it cannot insert raw HTML. Use this method for security against XSS if the popup content is user-provided.

Parameters

text(string)Textual content for the popup.

Returns

Popup: this

Example

var popup = new vietmapgl.Popup()
.setLngLat(e.lngLat)
.setText('Hello, world!')
.addTo(map);

toggleClassName(className)

Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.

Parameters

className(string)Non-empty string with CSS class name to add/remove

Returns

boolean: if the class was removed return false, if class was added, then return true

Example

let popup = new vietmapgl.Popup()
popup.toggleClassName('toggleClass')

trackPointer()

Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the setLngLat behavior. For most use cases, set closeOnClick and closeButton to false.

Returns

Popup: this

Example

var popup = new vietmapgl.Popup({ closeOnClick: false, closeButton: false })
.setHTML("<h1>Hello World!</h1>")
.trackPointer()
.addTo(map);

Events

close

Fired when the popup is closed manually or programatically.

Properties

popup(Popup): object that was closed

Example

// Create a popup
var popup = new vietmapgl.Popup();
// Set an event listener that will fire
// any time the popup is closed
popup.on('close', function(){
console.log('popup was closed');
});

open

Fired when the popup is opened manually or programatically.

Properties

popup(Popup): object that was opened

Example

// Create a popup
var popup = new vietmapgl.Popup();
// Set an event listener that will fire
// any time the popup is opened
popup.on('open', function(){
console.log('popup was opened');
});
  • Display a popup

  • Display a popup on hover

  • Display a popup on click

  • Attach a popup to a marker instance

IControl

src/ui/control/control.ts

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 vietmap GL JS's default control styling, add the vietmapgl-ctrl class to your control's node.

Example

// Control implemented as ES6 class
class HelloWorldControl {
onAdd(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'vietmapgl-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 = 'vietmapgl-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()

Optionally provide a default position for this control. If this method is implemented and Map#addControl is called without the position parameter, the value returned by getDefaultPosition will be used as the control's position.

Returns

ControlPosition: a control position, one of the values valid in addControl.

onAdd(map)

Register a control on the map and give it a chance to register event listeners and resources. This method is called by Map#addControl internally.

Parameters

map(Map)the Map this control will be added to

Returns

HTMLElement: The control's container element. This should be created by the control and returned by onAdd without being attached to the DOM: the map will insert the control's element into the DOM as necessary.

onRemove(map)

Unregister a control on the map and give it a chance to detach event listeners and resources. This method is called by Map#removeControl internally.

Parameters

map(Map)the Map this control will be removed from

Returns

undefined: there is no required return value for this method

NavigationControl

src/ui/control/navigation_control.ts

A NavigationControl control contains zoom buttons and a compass.

new NavigationControl(options: Object?)

Parameters

options(Object?)

Name Description
options.positionOptionsObjectdefault: A Geolocation API PositionOptions object.
options.fitBoundsOptionsObjectdefault: 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.trackUserLocationObjectdefault: 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.showAccuracyCircleObjectdefault: 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.showUserLocationObjectdefault: true By default a dot will be shown on the map at the user's location. Set to false to disable.

Example

var nav = new vietmapgl.NavigationControl();
map.addControl(nav, 'top-left');

Related

  • Display map navigation controls

  • Add a third party vector tile source

GeolocateControl

src/ui/control/geolocate_control.ts

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.

Extends Evented.

new GeolocateControl(options: Object?)

Parameters

options(Object?)

Name Description
options.positionOptionsObjectdefault: A Geolocation API PositionOptions object.
options.fitBoundsOptionsObjectdefault: 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.trackUserLocationObjectdefault: 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.showAccuracyCircleObjectdefault: 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.showUserLocationObjectdefault: 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 vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));

Instance Members

trigger()

Programmatically request and move the map to the user's location.

Returns

boolean: Returns false if called before control was added to a map, otherwise returns true .

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
geolocate.trigger();
});

Events

error

Fired on each Geolocation API position update which returned as an error.

Properties

data(PositionError): The returned PositionError object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition() .

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an error event occurs.
geolocate.on('error', function() {
console.log('An error event has occurred.')
});

geolocate

Fired on each Geolocation API position update which returned as success.

Properties

data(Position): The returned Position object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition() .

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a geolocate event occurs.
geolocate.on('geolocate', function() {
console.log('A geolocate event has occurred.')
});

outofmaxbounds

Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds.

Properties

data(Position): The returned Position object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition() .

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an outofmaxbounds event occurs.
geolocate.on('outofmaxbounds', function() {
console.log('An outofmaxbounds event has occurred.')
});

trackuserlocationend

Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationend event occurs.
geolocate.on('trackuserlocationend', function() {
console.log('A trackuserlocationend event has occurred.')
});

trackuserlocationstart

Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes).

Example

// Initialize the geolocate control.
var geolocate = new vietmapgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationstart event occurs.
geolocate.on('trackuserlocationstart', function() {
console.log('A trackuserlocationstart event has occurred.')
});

Related Locate the user

AttributionControl

src/ui/control/attribution_control.ts

An AttributionControl control presents the map's attribution information.

new AttributionControl(options: Object?)

Parameters

options(Object?)(default {})

Name Description
options.compactboolean? If true , force a compact attribution that shows the full attribution on mouse hover. If false , force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. Attribution should not be collapsed if it can comfortably fit on the map. compact should only be used to modify default attribution when map size makes it impossible to fit default attribution and when the automatic compact resizing for default settings are not sufficient.
options.customAttribution(string | Array)? (string | Array)?String or strings to show in addition to any other attributions.

Example

var map = new vietmapgl.Map({attributionControl: false})
.addControl(new vietmapgl.AttributionControl({
compact: true
}));

ScaleControl

src/ui/control/scale_control.ts

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 Description
options.maxWidthnumberdefault: '100' The maximum length of the scale control in pixels.
options.unitstringdefault: 'metric' Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).

Example

var scale = new vietmapgl.ScaleControl({
maxWidth: 80,
unit: 'imperial'
});
map.addControl(scale);

scale.setUnit('metric');

Instance Members

setUnit(unit)

Set the scale's unit of the distance

Parameters

unit(Unit)Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).

FullscreenControl

src/ui/control/fullscreen_control.ts

A FullscreenControl control contains a button for toggling the map in and out of fullscreen mode.

new FullscreenControl(options: Object?)

Parameters

options(Object?)

Name Description
options.containerHTMLElement? 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 vietmapgl.FullscreenControl({container: document.querySelector('body')}));

View a fullscreen map