Interact with the Map
User interface elements that can be added to the map. The items in this section exist outside of the map's canvas
element.
Controls
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 NMaps GL JS's
default control styling, add the nmapsgl-ctrl
class to your control's
node.
Example
// Control implemented as ES6 classclass HelloWorldControl {onAdd(map) {this._map = map;this._container = document.createElement('div');this._container.className = 'nmapsgl-ctrl';this._container.textContent = 'Hello, world';return this._container;} onRemove() {this._container.parentNode.removeChild(this._container);this._map = undefined;}} // Control implemented as ES5 prototypical classfunction HelloWorldControl() { } HelloWorldControl.prototype.onAdd = function(map) {this._map = map;this._container = document.createElement('div');this._container.className = 'nmapsgl-ctrl';this._container.textContent = 'Hello, world';return this._container;}; HelloWorldControl.prototype.onRemove = function () {this._container.parentNode.removeChild(this._container);this._map = undefined;};
Instance Members
NavigationControl
A NavigationControl
control contains zoom buttons and a compass.
Parameters
(Object?)
Example
const nav = new nmapsgl.NavigationControl();map.addControl(nav, 'top-left');
Related
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.
Parameters
(Object?)
Name | 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 nmapsgl.GeolocateControl({positionOptions: {enableHighAccuracy: true},trackUserLocation: true}));
Instance Members
Events
Related
AttributionControl
An AttributionControl
control presents the map's attribution information.
Parameters
(Object?)
(default {}
)Name | Description |
---|---|
options.compact boolean? | 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>)? | String or strings to show in addition to any other attributions. |
Example
const map = new nmapsgl.Map({attributionControl: false}).addControl(new nmapsgl.AttributionControl({compact: true}));
ScaleControl
A ScaleControl
control displays the ratio of a distance on the map to the corresponding distance on the ground.
Parameters
(Object?)
Example
const scale = new nmapsgl.ScaleControl({maxWidth: 80,unit: 'imperial'});map.addControl(scale); scale.setUnit('metric');
Instance Members
FullscreenControl
A FullscreenControl
control contains a button for toggling the map in and out of fullscreen mode.
Parameters
(Object?)
Name | 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 nmapsgl.FullscreenControl({container: document.querySelector('body')}));
Related
RotateControl
A RotateControl
control provides a button to tilt up the map according to pitch and bearing values.
Parameters
(Object?)
Name | Description |
---|---|
options.pitch number default: 70 | Sets the map's pitch (tilt). The pitch to set, measured in degrees away from the plane of the screen (0-60). |
options.bearing number default: -20 | Define the map's bearing (rotation). The bearing is the compass direction that is "up" (for example, a bearing of 90° orients the map so that east is up). |
options.minpitchzoom number default: null | Minimum zoom level for 3D mode. Default is null, i.e., stays at same zoom. |
Example
map.addControl(new nmapsgl.RotateControl({pitch: 45,bearing: 70}), 'bottom-right')
StyleControl
A StyleControl
control provides a set of buttons to switch between map styles.
Parameters
(Object?)
Name | Description |
---|---|
options.styles Array<Object>? | Variable that represents the styles on which it is possible to switch. It is an object array where each element represents a Style with:
By default, this variable contains the following styles: |
options.defaultStyle string default: "Streets" | Defines the style to be applied by default when the map is initialized.
If the
StyleControl
is used, the option 'defaultStyle' will override the style specified in the Map class constructor.
To avoid re-rendering the map style, initialize the map with the same style as defined in 'defaultStyle'. |
options.mapStyleIds Array<string>? | Allows you to filter part of the map styles defined in the "styles" variable.
mapStyleIds
must be specified in the form of an array of strings, where each string identifies the style by its label.
By default, all styles are presented to the user. |
Example
map.addControl(new nmapsgl.StyleControl({"defaultStyle": 'Dark',"mapStyleIds": ['Streets', 'Dark', 'Light'],}), 'top-left');
map.addControl(new nmapsgl.StyleControl({"defaultStyle": 'Streets',"styles": [{"label": 'Bright',"styleUrl": 'https://api.maptiler.com/maps/bright/style.json',},{"label": 'Streets',"styleUrl": 'https://api.maptiler.com/maps/streets/style.json',}]}), 'top-left');
GeocoderControl
A GeocoderControl
allows the user to search for places and Points of Interest (POIs). It's possible to do generic searches as well as reverse geocoding using this control.
Parameters
(Object?)
Example
const geocoder = new nmapsgl.GeocoderControl({zoom: 14,flyTo: false,limit: 3});map.addControl(geocoder);
DirectionsControl
A DirectionControl
allows the user to search for a route between 2 points: origin and destination (which can be reversed). The search point can be a generic search (streets, cities, points of interest, etc) as well as a reverse geocode. The route profiles to be used can be defined in this control, which can be customized by the user with route options (avoids and units).
Parameters
(Object?)
Name | Description |
---|---|
options.zoom number default: 16 | Defines zoom level after selecting the search result. |
options.flyTo boolean default: true | Adds the fly effect to the selected search. |
options.traffic boolean default: false | Consider traffic on route calculation. |
options.limit number default: 5 | Number of results to be presented in the search. |
options.units string default: 'Metric' | Unit of the distance (
'Metric'
or
'Imperial'
).
|
options.profileIds Array<string> default: ['Car','Truck','Walking'] | Available profiles for routing:
'Car'
,
'Truck'
,
'Walking'
.
|
options.routingOptions Array<string> default: ['Motorways','Tolls','Ferries','Freeways','Uturns','Small Roads','Country Crossing','Unpaved','Tunnels'] | Available options for routing:
'Motorways'
,
'Tolls'
,
'Ferries'
,
'Freeways'
,
'Uturns'
,
'Small Roads'
,
'Country Crossing'
,
'Unpaved'
,
'Tunnels'
.
|
Example
const directions = new nmapsgl.DirectionsControl({zoom: 14,flyTo: false,traffic: true,limit: 3,profileIds: ['Car', 'Walking'],routingOptions: ['Motorways', 'Tolls', 'Ferries']});map.addControl(directions);
StreetViewControl
A StreetViewControl
allows the user to view end-to-end street-level images. When selecting a sequence or a point in the sequence of images, a Viewer is added to navigate through them.
Example
const streetview = new nmapsgl.StreetViewControl();map.addControl(streetview);
Handlers
BoxZoomHandler
The BoxZoomHandler
allows the user to zoom the map to fit within a bounding box.
The bounding box is defined by clicking and holding shift
while dragging the cursor.
Instance Members
ScrollZoomHandler
The ScrollZoomHandler
allows the user to zoom the map by scrolling.
Instance Members
DragPanHandler
The DragPanHandler
allows the user to pan the map by clicking and dragging
the cursor.
Instance Members
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.
Instance Members
KeyboardHandler
The KeyboardHandler
allows the user to zoom, rotate, and pan the map using
the following keyboard shortcuts:
=
/+
: Increase the zoom level by 1.Shift-=
/Shift-+
: Increase the zoom level by 2.-
: Decrease the zoom level by 1.Shift--
: Decrease the zoom level by 2.- Arrow keys: Pan by 100 pixels.
Shift+⇢
: Increase the rotation by 15 degrees.Shift+â‡
: Decrease the rotation by 15 degrees.Shift+⇡
: Increase the pitch by 10 degrees.Shift+⇣
: Decrease the pitch by 10 degrees.
Instance Members
DoubleClickZoomHandler
The DoubleClickZoomHandler
allows the user to zoom the map at a point by
double clicking or double tapping.
Instance Members
TouchZoomRotateHandler
The TouchZoomRotateHandler
allows the user to zoom and rotate the map by
pinching on a touchscreen.
They can zoom with one finger by double tapping and dragging. On the second tap, hold the finger down and drag up or down to zoom in or out.
Instance Members
TouchPitchHandler
The TouchPitchHandler
allows the user to pitch the map by dragging up and down with two fingers.
Instance Members
Events
The different types of events that NMaps GL JS can raise.
You can also find additional event documentation for: Map
, Marker
, Popup
, and GeolocationControl
.
MapMouseEvent
MapMouseEvent
is the event type for mouse-related map events.
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
MapTouchEvent
MapTouchEvent
is the event type for touch-related map events.
Instance Members
NMapsZoomEvent
A NMapsZoomEvent
is the event type for the boxzoom-related map events emitted by the BoxZoomHandler.
Properties
(MouseEvent)
: The DOM event that triggered the boxzoom event. Can be a
MouseEvent
or
KeyboardEvent
MapDataEvent
A MapDataEvent
object is emitted with the Map.event:data
and Map.event:dataloading events. Possible values for
dataType
s are:
'source'
: The non-tile data associated with any source'style'
: The style used by the map
Properties
(boolean?)
: True if the event has a
dataType
of
source
and the source has no outstanding network requests.
(Object?)
: The style spec representation of the source if the event has a
dataType
of
source
.
(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
,
content
and
visibility
.
(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.
(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.
Instance Members
Control Zoom and Pan
The usage of a map on a web page may require specific options to control the way users interact with the map to zoom and pan. These options, such as minZoom
, maxZoom
and bounds
, are defined in the parameters of the Map
object.
Default Behaviour
The following map demonstrates the default behaviour for map interactions with a map instantiated with only the zoom and center options defined.
The code for this map is below:
let map = new nmapsgl.Map({ container: 'map', center: [-73.9978, 40.7209], zoom: 13, style: 'Streets'});
Controlling Gesture Handling
When a user scrolls a page that contains a map, the scrolling action can unintentionally cause the map to zoom. This is the default behavior given by ScrollZoomHandler
. To prevent user scrolling interactions from zooming a map, disable the event handler.
The code for this map is below:
let map = new nmapsgl.Map({ container: 'map', center: [-73.9978, 40.7209], zoom: 13, style: 'Streets'}); // disable map zoom when using scrollmap.scrollZoom.disable();
Disabling Pan and Zoom
To avoid zoom and pan the map, the handlers DragPanHandler
and ScrollZoomHandler
should be disabled.
The code for this map is below:
let map = new nmapsgl.Map({ container: 'map', center: [-73.9978, 40.7209], zoom: 13, style: 'Streets'}); // disable map zoom when using scrollmap.scrollZoom.disable(); // disable panmap.dragPan.disable();
Restricting Map Bounds and Zoom
It may be desireable to allow gestures and zoom controls but restrict the map to a particular bounds or a minimum and maximum zoom. To do this, the options bounds
, minZoom
andmaxZoom
must be set.
The code for this map is below:
let bounds = [ [-74.04728, 40.68392], // [west, south] [-73.91058, 40.87764] // [east, north]]; let map = new nmapsgl.Map({ container: 'map', center: [-73.9978, 40.7209], zoom: 13, style: 'Streets', maxBounds: bounds, minZoom: 12, maxZoom: 18});