Viewer API version v5.17.2
Table of Contents
- om
- OMApi
- OMEvents
- OMSearch
- AutocompleteSuggestion
- ReverseGeocodeResult
- OMMap
- OMSketch
- OMMeasure
- OMLayer
- LayerEditController
- OMTree
- OMTreeNode
- OMGeolocation
- OMGeoPosition
- OMGeolocationResult
- OMEdit
- OMUtils
- OMInfoLinks
- OMSearchEngines
- OMFeatureInfo
- OMFilter
om
The global Onemap api. After loading the viewer library, this global is available as window.om. For backwards compatibility, the global is also still accessible through window.wgp.
Type: Object
initViewer
This is the entry point for initializing the Onemap viewer that initializes the viewer with a config object into a container DOM node. It returns a promise that resolves with an api instance that can be used to control that viewer.
Parameters
initialAppConfig
Object The viewer configuration object obtained from the Onemap backend.containerElement
HTMLElement A DOM-node that will host the Onemap viewer.-
options
object Options. (optional, default{}
)options.customMessages
object? Optional translations for the viewer. When given, the viewer will use these translations instead of trying to fetch its own translations over the network.options.moveTolerance
number? Optional movement tolerance in pixels. This is used in the mobile display to differentiate between a touch and touch + drag. Defaults to 5 pixels.options.forceMobileLayout
boolean? Force mobile layout. When true, the viewer will always use the mobile device layout, even for fullscreen and embedded viewers. Default false.options.allowInlineStyles
boolean? When false, disable viewer components that inject style elements into the DOM. Blocking these may be necessary for embedded viewers that use a strict Content Security Policy. Default true.options.useNativeSelect
boolean? When true, use native html select input component. Default false.options.applyOffsetCorrection
boolean? Set to true if select option menus are displaced relative to the input box. This can happen in some embedded maps that are offset from the top left of a web page. Default false.options.enableScrollZoom
boolean? Set to true to enable zoom on mouse scroll. This is disabled by default for embedded maps.options.mapParams
object? Optional map parameters to merge into existing map parameters on init.options.snapshot
object? Optional snapshot object (created by api.map.createSnapshot) which will be applied on init.
Examples
// Initialize a viewer from a map config object.
const appConfig = {...}; // Replace this with an actual app config object.
// Point Onemap to the folder containing the Onemap viewer library code and assets.
om.setBaseUrl('./lib/');
// Initialize the viewer in a div with id 'om-viewer'.
om.init(appConfig, document.getElementById('om-viewer')).then(api => {
// Use returned api object to control the viewer.
console.log('Viewer api ready for use.');
});
Returns Promise<OMApi> The Onemap api instance for the initialized viewer.
setAssetBaseUrl
Set the onemap asset folder url. Call this method before calling initViewer to set the name and location of the Onemap lib folder.
Parameters
url
string The app root url. Defaults to ‘/’.
Returns void
setJwtToken
Set the JWT token used to call Onemap endpoints that require authorization.
Parameters
jwtToken
string The JWT token.
Returns void
setOMServerUrl
Set the onemap server url. Set this url if you use any services that require authorization via the (possibly remote) Onemap proxy.
Parameters
url
string The Onemap server url. Defaults to ‘/’ for self-hosted Onemap installations.
Returns void
fetchMapConfig
Fetch a configuration object for a specific map. Note: JWT token has to be set before calling this method.
Parameters
Returns Promise<object> A promise that will resolve with a map configuration object.
OMApi
The Onemap api object returned from initViewer, do not instantiate directly
Parameters
options
(optional, default{}
)
events
Properties
events
OMEvents Event bus.
updateMapParams
Update one or more map parameters by supplying an object. Values present in the supplied object will be updated. Also updates the values of the current_date and current_datetime map parameters.
Parameters
params
object Object with parameters to update.
Returns void
destroy
Destroy the map associated with this API instance. Call this method before initializing a new map in this map’s DOM Node.
Returns void
search
An instance of OMSearch to perform dynamic searches.
Type: OMSearch
map
An instance of OMMap to control the viewer after initialization.
Type: OMMap
sketch
An instance of OMSketch to control the viewer after initialization.
Type: OMSketch
measure
An instance of OMMeasure to control the viewer after initialization.
Type: OMMeasure
tree
An instance of OMTree to read and manipulate the layer tree after viewer initialization.
Type: OMTree
geolocation
An instance of OMGeolocation to handle geolocation functionality after viewer initialization.
Type: OMGeolocation
edit
An instance of OMEdit to handle editing after viewer initialization.
Type: OMEdit
utils
An instance of OMUtils containing general utility functions available after viewer initialization.
Type: OMUtils
featureInfo
An instance of OMFeatureInfo for reading and controlling feature info display after viewer initialization.
Type: OMFeatureInfo
getMapParams
Get an object containing the currently set map parameters.
Returns object Current map parameters object.
OMEvents
The Onemap event bus used for transmitting events from the viewer.
on
Register an event handler for an event type.
Parameters
eventName
string The event to listen for, or ‘*’ to listen to any event.eventHandler
function The event handler. The handler will be called with a single event arg for a named event. The handler will be called with eventName and eventArg when the handler is registered as a wildcard handler.
Examples
api.events.on('map.click', ({ coordinate }) => {
console.log(`User clicked here: (${coordinate.join()}).`);
});
api.events.on('*', (eventName, evt) => {
if (eventName === 'map.move') {
console.log('Map moved to ', evt.center);
}
});
Returns void
once
Register an event handler for an event type, but the handler is immediately unregistered after handling the event.
Parameters
eventName
string The event to listen for, or ‘*’ to listen to any event.eventHandler
function The event handler. The handler will be called with a single event arg for a named event. The handler will be called with eventName and eventArg when the handler is registered as a wildcard handler.
Examples
api.events.once('map.click', ({ coordinate }) => {
console.log(`User clicked here: (${coordinate.join()}).`);
});
Returns void
off
Unregister an event handler for an event type.
Parameters
Examples
function handleClick() { ... }
api.events.off('map.click', handleClick);
Returns void
FeatureInfoResult
Feature info for a single feature.
Type: object
Properties
layerId
string The id of the layer containing the feature.featureId
string The id of the feature.properties
object The raw properties of the feature.html
string The templated feature info.geometry
GeoJSONGeometry The feature geometry as GeoJSON geometry.
FeatureInfoError
Feature info for a single feature.
Type: object
Properties
FeatureInfoSlide
Feature info slide properties.
Type: object
Properties
index
number The currently visible slide index.layerId
string The id of the layer containing the feature.featureId
string The id of the feature corresponding to the visible slide.properties
object The raw properties of the feature.geometry
GeoJSONGeometry The feature geometry in map projection. Null if no geometry is available.
featureInfo.requested
Emitted after use requests feature info by clicking on the map with the info tool active.
Type: object
Properties
featureInfo.received
Emitted after feature info results have been obtained.
Type: object
Properties
results
Array<FeatureInfoResult> An array of feature info results, one result per feature near the feature info request location.errors
Array<FeatureInfoError> An array of error objects for each layer that gave an error when attempting to get feature info.
featureInfo.slideChanged
Emitted after a single feature info slide is first displayed or when the visible slide changed.
Type: object
Properties
currentSlide
FeatureInfoSlide Properties of the currently visible feature info. The currentSlide property is null when feature info is closed or otherwise ceases to be visible.
featureInfo.cleared
Emitted after feature info is cleared by the user (or through the API).
edit.transactionStarted
Emitted when edit transaction starts for a layer.
Type: object
Properties
layerId
string Layer id.
edit.transactionSuccess
Emitted after edit transaction succeeds for a layer.
Type: object
Properties
layerId
string Layer id.
edit.transactionError
Emitted if edit transaction fails for a layer.
Type: object
Properties
edit.featuresInserted
Emitted after new features have been sucessfully inserted into a layer.
Type: object
Properties
layerId
string Layer id.features
Array<GeoJSONFeature> An array of GeoJSON features that have been inserted.
edit.featureGeometryUpdated
Emitted after a feature geometry has been successfully updated.
Type: object
Properties
layerId
string Layer id.featureId
string Id of the feature to update.geometry
GeoJSONGeometry The new geometry as GeoJSON geometry.
edit.featurePropertiesUpdated
Emitted after feature properties have been successfully updated.
Type: object
Properties
layerId
string Layer id.featureId
string Id of the feature to update.properties
object New feature properties. Contains only properties that were updated.
edit.featuresDeleted
Emitted after features are deleted from a layer.
Type: object
Properties
layerId
string Layer id.featureIds
Array<string> An array of feature id’s that have been deleted from the layer.
map.mouseMove
Emitted when the mouse cursor position changes. Mouse position has the same projection as the map.
Type: object
Properties
coordinate
(Array<number> | null) The mouse pointer coordinate in map projection. Coordinate is null when the cursor leaves the map or hovers over a UI interface element.
map.rotate
Emitted when the rotation of the map changes.
Type: object
Properties
rotation
number The map rotation in radians.
map.click
Emitted when the user clicks on the map. Click position has the same projection as the map.
Type: object
Properties
coordinate
Array<number> The map click coordinate in map projection.lonlat
Array<number> Map click coordinate in CRS:84 as [lon, lat].
features.clicked
Emitted when the user clicks on vector features on the map. It contains a hits lookup with clicked feature id’s per layer id.
Type: object
Properties
hits
object Hit lookup table. Each layer id in this object contains an array of feature ids.
map.move
Emitted after map viewport has changed. This event is not emitted during map drag/rotation.
Type: object
Properties
center
Array<number> The map center as [x, y] in map projection.zoom
number The zoom level.resolution
number The map resolution.rotation
number The map rotation in radians in clockwise direction.
layer.loadStart
Emitted when a layer starts loading data.
Type: object
Properties
layerId
string The layer id.
layer.loadEnd
Emitted when all data has been loaded for a layer.
Type: object
Properties
layerId
string The layer id.
layer.loadError
Emitted when a layer cannot be loaded completely because of a network and/or service error.
Type: object
Properties
layer.selectionChanged
Emitted when the selected feature set of a layer changes.
Type: object
Properties
layer.visibilityChanged
Emitted when layer visibility changes.
Type: object
Properties
layerId
string The layer id.visibility
bool The new layer visibility.
sketch.complete
Emitted when the user finishes drawing a sketch. Note: the coordinates of the feature are in map projection!
Type: object
Properties
feature
object The sketch as GeoJSON feature.
sketch.modified
Emitted when the user modifies a a sketch feature. Note: the coordinates of the feature are in map projection!
Type: object
Properties
feature
object The modified feature as GeoJSON feature.
sketch.error
Emitted when the user draws an invalid sketch geometry.
Type: object
Properties
message
string The error message.
sketch.newPoint
Emitted when a new vertex is added to a sketch geometry. Since polygons are always closed, the first point will be emitted as newPoint when finalizing a polygon drawing. To check if a new point is a polygon self-closing point, check the closingPoint flag of the event.
Type: object
Properties
coordinates
Array<Number> The coordinates of the new vertex.selfClosingPoint
bool Equals true when the new point is the point that closes a polygon.
measure.complete
Emitted when the user finishes drawing a measure. Note: the coordinates of the feature are in map projection!
Type: object
Properties
feature
object The measure as GeoJSON feature.
measure.error
Emitted when the user draws an invalid measure geometry.
Type: object
Properties
message
string The error message.
OMSearch
An object for performing dynamic searches without using the search elements in the viewer. Do not instantiate this class directly. A OMSearch instance is provided as api.search after initializing a viewer. The search engine uses PDOK Locatieserver under the hood.
getSuggestions
Search for autocomplete suggestions for a given search query. Up to ten matches are returned ordered by descending match score.
Parameters
-
query
object The search query parameters.
Returns Promise<Array<AutocompleteSuggestion» A promise that resolves with an array of autocomplete suggestions.
executeSearch
Search for best matching result for the given query. The centroid of the result is returned as a GeoJSON feature collection in CRS:84 projection. If you want to nagivate to the result in the viewer, you can do that as follows:
Parameters
-
query
object The search query parameters.
Examples
api.search.executeSearch(query).then(featureCollection => {
const feature = featureCollection.features[0];
// Result may be empty if no match is found, so don't forget to check.
if (feature) {
const [lon, lat] = feature.geometry.coordinates;
api.map.setCenter([lon, lat], {
srid: 'CRS:84',
// zoom: 14, // optional zoom level
});
}
});
Returns Promise<GeoJSON> A promise that resolves with a the query results as GeoJSON point feature collection.
reverseGeocode
Parameters
Returns Promise<ReverseGeocodeResult> A promise that resolves with the reverse geocoding result.
AutocompleteSuggestion
OMSearch autocomplete suggestion result.
Type: Object
Properties
value
any Search result value.label
string Search result display label as text.formattedLabel
string? If the search engine supports it, formattedLabel contains the search result formatted as HTML with matching parts highlighted.
ReverseGeocodeResult
OMSearch reverse geocode result.
Type: Object
Properties
formattedLocation
string Location description as formatted string.data
object? Optional object with properties describing the location.geometry
object? Location as GeoJSON geometry (in CRS:84, if the geocode service provides one).
OMMap
An object for controlling the map in the viewer. Do not instantiate this class directly. A OMMap instance is provided on api.map after initializing a viewer.
getViewParams
Get current view parameters like center/extent/zoom level. Returns an object with:
- center: current map center in map projection.
- extent: current view extent in map projection.
- zoom: current zoom level.
- resolution: current approximate resolution in map units/pixel.
- pointResolution: current calculated resolution in meters/pixel.
- rotation: current map rotation in degrees clockwise.
Returns object Current view params.
zoomIn
Zooms the map in one step.
Returns void
zoomOut
Zooms the map out one step.
Returns void
zoomToExtent
Zoom to a given extent. The viewport will try to match the given extent as closely as possible, taking into account minimum and maximum visible extent allowed by the map configuration.
Parameters
extent
Array<number> Bounds array: [left, bottom, right, top].-
options
object Extra options for zooming to extent. (optional, default{}
)
Returns void
zoomToInitialExtent
Zoom to initial map extent.
Returns void
zoomToFeatures
Zoom to the extent of a GeoJSON feature collection. The viewport will try to match the given extent as closely as possible, taking into account minimum and maximum visible extent allowed by the map configuration.
Parameters
featureCollection
GeoJSONFeatureCollection GeoJSON feature collection.-
options
object Extra options for zooming to extent. (optional, default{}
)
Returns void
zoomToSelection
Zoom to the extent of all selected features.
Parameters
-
options
object Extra options for zooming to extent. (optional, default{}
)options.maxZoom
number? The maximum zoom level to zoom to. Default 24. Use this option when the extent is very small.
Returns void
zoomToLayer
Zoom the map to fit the contents of a vector layer. This function does nothing when called on an image based layer.
Parameters
layer
OMLayer A Onemap layer wrapper.-
options
object Options. (optional, default{}
)options.maxZoom
number? Max zoom level. Useful when the layer contains a single feature.
Returns void
setCenter
Reposition the map to a new center.
Parameters
center
Array<number> Center as [x, y].-
options
object Extra options for zooming to extent. Note: zoom result may be restricted by map settings. (optional, default{}
)options.srid
string? The spatial reference id of the given center, e.g. ‘EPSG:4326’. If no SRID is given, the map SRID is assumed.options.zoom
number? The zoom level to set on the map. When given the map zoom is set as wel as the new center.options.zoomRadiusM
number? Optional zoom distance in meters. Can be used instead of an integer zoom level. When given, zoom in to the largest integer zoom level such that a circle with radius zoomRadiusM fits in the viewport.
Returns void
setRotation
Set the rotation of the map.
Parameters
rotation
number Rotation of map in radians.
Returns void
setSelectActive
Switch selection mode on or off. In selection mode, map clicks add features to the layer’s selected feature set. Alt+Clicking a feature removes it from the selection set.
Parameters
active
bool Selection mode active state. Set to true or false to turn selection mode on or off, respectively.
Returns void
getLayer
Get the layer wrapper instance for a layer with given layer id.
Parameters
layerId
string The layer id.
Returns OMLayer A Onemap layer wrapper instance or undefined when no layer with given id can be found in the map.
getLayers
Get an array of layer wrappers in top-to-bottom layer tree order.
Returns Array<OMLayer> An array of layers in top-to-bottom layer tree order.
getLayersByTitleOrName
Get an array of layer wrappers for layers with matching title or name.
Parameters
titleOrName
string The layer title or name to match. Layer title is the title of the layer in the viewer. Layer name is the name of the layer as listed in the layer’s service capabilities document.
Returns Array<OMLayer> An array of OMLayer instances matching the title or name.
requestFullscreen
Make the map container full screen (if allowed). This method needs to be called from within an event handler or otherwise it will be denied.
Returns void
exitFullscreen
Exit full screen mode. This method needs to be called from within an event handler or otherwise it will be denied.
Returns void
fullscreenEnabled
Check if fullscreen mode is enabled for this page.
Returns boolean True if fullscreen mode is enabled;
applySnapshot
Create snapshot of current map viewer state.
Parameters
snapshot
object Map snapshot object.
Returns void
createSnapshot
Create snapshot of current map viewer state.
Returns object Map snapshot object.
OMSketch
An object for controlling the map in the viewer. Do not instantiate this class directly. A OMSketch instance is provided as api.sketch after initializing a viewer.
start
Switch the viewer to sketch mode.
Parameters
sketchMode
string One of Point, LineString, Polygon, Circle, or Box.-
options
object Sketch options.options.clearPrevious
boolean When true, previous sketches with the same category are cleared after finishing a new one. Default true.options.stopAfterSketch
boolean When true, sketch.stop() is called automatically after finishing a sketch. Default false.options.addSketchToMap
boolean When true, the sketch is added to the map after firing the sketchComplete event. Default true.options.category
string When added to the map, features will get this category tag. Default value ‘sketchDefault’.options.freehand
bool When true, drawing operates in freehand mode. Does nothing for mode Point or Circle. Default false.options.toolAction
string Action of the tool used for sketch. For internal use only. Defaults to ‘api-sketch’.
stop
Stop sketching in the map. This cancels the current sketch being drawn.
Returns void
startEditing
Start a feature modify interaction in the map. This cancels any sketch in progress. When the mouse cursor moves near a feature edge or vertex it turns into a control point. Click and drag the control point to move it, modifying the feature.
Returns void
stopEditing
Stop the feature modify interaction in the map.
Returns void
clear
Clear the sketch layer by removing all sketch features for a given category. If no category is given, only removes sketch features that have been drawn by the user (sketchDefault category).
Parameters
category
string? Clear sketches with this category property value. Use ‘*’ to clear all sketch features. (optional, default'sketchDefault'
)
Returns void
addFeatures
Adds features to the sketch layer. Features will be transformed to map projection. If the source features are not in lon/lat (CRS:84), you have to supply the source srid as options.sourceSrid.
It is possible to style features by adding style parameters to the feature properties. See the SketchStyleProps type definition for available style parameters.
Parameters
features
object A GeoJSON feature collection.-
options
object Options.options.srid
string SRS identifier string of source data projection. When not given, CRS:84 is assumed as per GeoJSON specification.options.sourceSrid
string deprecated Same as srid, but will be deprecated in a later version. Use options.srid instead.options.category
string Sketch category. Default value is ‘sketchDefault’.
Returns void
getFeatures
Get sketch features as GeoJSON feature collection.
Returns GeoJSONFeatureCollection GeoJSON feature collection of all sketch features in map projection.
getFeatureById
Get sketch feature by ID.
Parameters
featureId
string Sketch feature ID.
Returns GeoJSONFeature GeoJSON feature with the specified ID.
getSelectedFeatures
Get selected sketch features as GeoJSON feature collection.
Returns GeoJSONFeatureCollection GeoJSON feature collection of all selected sketch features in map projection.
updateFeature
Update a single sketch feature by providing an updateFeature as GeoJSON feature. The feature with the same id as the updateFeature will be updated. If the update feature has a geometry, the geometry will be updated. If the update feature has properties, the properties of the feature will be updated.
Parameters
updateFeature
GeoJSONFeature The update feature.
Returns void
deleteFeature
Remove a single sketch feature by id.
Parameters
featureId
string ID of feature to remove.
Returns void
deleteSelectedFeatures
Remove selected sketch features.
Returns void
selectFeaturesById
Select sketch features by id.
Parameters
Returns void
unselectFeaturesById
Unselect sketch features by id.
Parameters
Returns void
unselectAll
Unselect all selected sketch features.
Returns void
selectFeaturesByGeometry
Select sketch features intersecting the given query geometry.
Parameters
queryGeometry
GeoJSONGeometry Query geometry in map projection.-
options
object Options.options.within
boolean? If true, only select features entirely within the given geometry. Default false.
Returns void
SketchStyleProps
Sketch style properties.
Type: object
Parameters
strokeWidth
number Stroke width in css pixels.strokeColor
string Stroke color as #ABCDEF hex string.strokeOpacity
number Stroke opacity (number between 0 and 1).fillColor
string Fill color as #ABCDEF hex string.fillOpacity
number Fill opacity (number between 0 and 1).pointRadius
number Point radius in css pixels.
OMMeasure
An object for controlling measurements in the map. Do not instantiate this class directly. A OMMeasure instance is provided as api.measure after initializing a viewer.
start
Switch the viewer to measure mode.
Parameters
stop
Stop measuring in the map. This cancels the current measure being drawn.
Returns void
clear
Clear the measure layer by removing all measure features.
Returns void
getFeatures
Get measurements as GeoJSON feature collection. This includes circle radial lines and measurement labels.
Returns GeoJSONFeatureCollection GeoJSON feature collection of all measurements in map projection.
OMLayer
An api wrapper for working with layers in the Onemap viewer. Do not instantiate this class directly, but use a map api method for obtaining a wrapper for a layer from the map. Methods that perform an action on the layer return the layer wrapper to make it easy to apply multiple actions in a chain.
Properties
id
string The Onemap layer id.title
string The layer title.name
string The layer name as advertised in the capabilitites document of the layer’s service.identifierFields
Array<string> An array of field names that identify features in the layer.fields
object A hashmap of fieldname -> field type as string. Note: for OGC layers, the field type is taken as-is from the layer capabilities document without xsd:-prefix.geometryFieldName
string The name of the geometry field. Equals null for non-WFS layers.
getFeatures
Gets a layer’s features as a GeoJSON feature collection object. The features will be returned in the same projection as the map, unless options.srid is specified. Returns an empty featureCollection if the layer does not have a vector source.
Parameters
-
options
object Options.options.srid
string? When given, Onemap will transform the features to the projection with the requested SRS identifier. Use CRS:84 to conform to the GeoJSON standard. GetGeoJSONFeatures will throw when the requested projection is not available.options.bbox
Array<number>? When given, only return features whose bbox intersects the given bbox. Bbox projection must equal the map projection.options.queryGeometry
GeoJSONGeometry? When given, return only those features that intersect the given query geometry. The query geometry must be in map projection. The bbox option is ignored when querying with geometry.options.within
bool? If true, only return features fully within the query geometry. Default false.
Returns object The layer’s features as GeoJSON feature collection.
getFeatureById
Gets a feature by feature id from the layer as a GeoJSON feature. The feature will be returned in the same projection as the map, unless options.srid is specified. Returns null if the feature with the given id does not exist in the layer or if the layer does not have a vector source.
Parameters
featureId
string The id of the feature.-
options
object Options.options.srid
string When given, Onemap will transform the features to the projection with the requested SRS identifier. Use CRS:84 to conform to the GeoJSON standard. GetGeoJSONFeatures will throw when the requested projection is not available.
Returns object A GeoJSON feature with the requested id.
addFeatures
Adds features to a vector layer. Features will be transformed to map projection. If the source features are not in lon/lat (CRS:84), you have to supply the source srid as options.sourceSrid.
Parameters
Returns void
loadWfsGeoJSONFeatures
Loads features from WFS layer source as GeoJSON. If the source is not a WFS source, this method property will be undefined.
Parameters
bbox
Array<number> The bbox used in the GetFeatures request. Set this to null to request features without bbox.-
options
object Loader options.options.srid
string The projection srid for the requested features. When not provided, the map srid will be used. If a bounding box is provided, it must be in the projection indicated by the given srid.options.filter
OMFilter An optional filter used to load the features. This filter will be combined with the bbox parameter, if any is provided.
removeAllFeatures
Removes all features from a vector layer.
Returns void
reload
Reload the layer. This only works for layers that request data from a remote source.
Returns void
highlightFeatures
Highlights features in a vector layer.
Parameters
Returns void
unhighlightFeatures
Unhighlights features in a vector layer.
Parameters
Returns void
setVisible
Change the visibility of the layer.
Parameters
visible
bool The layer visibility.
Returns OMLayer The OMLayer instance.
getVisible
Get current layer visibility.
Returns bool Current layer visibility.
setStyle
Change the style of a WMS or vector layer. For WMS layers, style is the style name as advertised by the service. For vector layers, style is an SLD XML string.
Parameters
style
string WMS style name, or SLD XML for vector layers.
Returns OMLayer The OMLayer instance.
getStyle
Get currently active layer style. For WMS layers, style is the style name as advertised by the service. For vector layers, style is an SLD XML string.
Returns string The currently active layer style.
setOpacity
Change the opacity of a layer.
Parameters
opacity
double The new layer opacity as a number between 0 and 1.
Returns OMLayer The OMLayer instance.
setDefaultFilter
Set a default filter on a layer, or remove a default filter from a layer. Setting or removing a filter automatically reloads the layer if it’s a WFS layer.
Parameters
filter
OMFilter The layer filter as a filter description object. Set the filter to null to remove the filter from the layer.
Examples
// A simple comparison filter
myLayer.setDefaultFilter({
type: 'comparison',
operator: 'propertyisequalto',
propertyname: 'category',
literal: 'vegetables'
});
// Multiple constraints using 'and'.
myLayer.setDefaultFilter({
type: 'and',
predicates: [
{
type: 'comparison',
operator: 'propertyisequalto',
propertyname: 'class',
literal: 'birds'
},
{
type: 'comparison',
operator: 'propertyislike',
propertyname: 'name',
literal: '*penguin*'
}
]
});
Returns OMLayer The OMLayer instance.
hideFeatures
Hide features within the layer by id. Hidden features cannot be interacted with and are not returned by get(Selected)Features.
Note: hidden features can become unhidden when the layer filter changes.
Parameters
Returns void
unhideFeatures
Unhide features within the layer by id.
Parameters
Returns void
unhideAllFeatures
Unhide all features within the layer.
Returns void
selectFeatures
Select features within the layer by id.
Parameters
Returns void
unselectFeatures
Unselect features within the layer by id.
Parameters
Returns void
clearSelectedFeatures
Unselect all selected features within the layer.
Returns void
getSelectedFeatures
Gets all selected features within the layer features as a GeoJSON feature collection object. The features will be returned in the same projection as the map, unless options.srid is specified. Throws an error if the layer’s source does not have a getFeatures method.
Parameters
-
options
object Options.options.srid
string When given, Onemap will transform the features to the projection with the requested SRS identifier. Use CRS:84 to conform to the GeoJSON standard. GetGeoJSONFeatures will throw when the requested projection is not available.
Returns object The layer’s features as GeoJSON feature collection.
selectFeaturesWithFilter
Select all features matching a filter.
Parameters
omFilter
OMFilter Onemap filter description object.
zoomToDataExtent
Zoom to the extent of the data in a vector layer. Calling this method on a layer without a vector source does nothing.
Parameters
-
options
object Options. (optional, default{}
)options.maxZoom
number? By default, the viewer zooms to at most zoom level 15 when the layer data extent is very small. Use this option to override the max zoom level.
Returns OMLayer The OMLayer instance.
zoomToSelectedFeatures
Zoom to the extent of the selected features in a vector layer. Calling this method on a layer without selected features does nothing.
Parameters
-
options
object Options. (optional, default{}
)options.maxZoom
number? By default, the viewer zooms to at most zoom level 15 when the selection extent is very small. Use this option to override the max zoom level.
Returns OMLayer The OMLayer instance.
getFeaturesIntersectingGeometry
Get features from a layer intersecting a given geometry.
Parameters
geometry
GeoJSONGeometry GeoJSON geometry. Coordinates must be in map projection.-
options
object Options.options.within
boolean? If true, only select features entirely within the given geometry. Default false.
Returns Array<GeoJSONFeature> An array of GeoJSON features intersecting the input geometry.
selectFeaturesIntersectingGeometry
Select features within the layer intersecting a given GeoJSON geometry.
Parameters
geometry
GeoJSONGeometry GeoJSON geometry. Coordinates must be in map projection.-
options
object Options.options.within
boolean? If true, only select features entirely within the given geometry. Default false.
Returns void
edit
Edit controller for the layer. Note: call the .supportsEditing method of the controller to find out if editing is supported for the layer.
LayerEditController
An api wrapper for controlling edits on a layer through a registered edit protocol function. Do not instantiate this class directly, but access it through the OMLayer.edit property.
Properties
id
string The Onemap layer id.
supportsEditing
Check whether editing is supported for the layer.
Returns bool True if editing is supported.
processTransaction
Process a single edit transaction. You can process a mix of inserts, updates and deletes.
Parameters
inserts
Array<GeoJSONFeature> An array of GeoJSON features to insert. The coordinates have to be in the layer’s default projection.updates
Array<GeoJSONFeature> An array of GeoJSON features to update. Each feature should have an id equal to the id of the feature you want to update. If the feature has a geometry, the geometry will be updated. The coordinates have to be in the layer’s default projection. If the feature has a properties block, only the properties present in the feature will be updated.deletes
Array<string> An array of feature ids to delete.-
options
object Transaction options. (optional, default{}
)options.resumeOnTransactionError
boolean? Default false. If true, treat a failed transaction as success. This unblocks the layer from performing another transaction.options.reloadAfterEdit
boolean? Default false. By default, edits are applied in-memory to the loaded features. Setting this option to true forces a full layer reload after transaction success.
Returns Promise A promise that resolves when the edit transaction succeeds, or fails with an error message detailing the reason the edit failed.
showFeatureUpdateForm
Show an interactive form for editing attributes of a single feature, or multiple features at once.
Parameters
featureIdArray
(string | Array<string>) The id of the feature to edit or an array of feature ids. Will throw an error if one or more features cannot be found in the layer. Will also throw if another transaction is still in progress.deselectAfterSave
bool When true, deselect edited features after update. Default false.
showFeatureInsertForm
Show an interactive form for editing attributes of new feature to insert into the layer data source. Will throw if another transaction is still in progress.
Parameters
geometry
GeoJSONGeometry The GeoJSON geometry of the feature to insert into the layer data source. This geometry has to be in the layer’s default projection.
OMTree
An object for controlling the layer tree in the viewer. Do not instantiate this class directly. A OMTree instance is provided on api.tree after initializing a viewer.
getLayerTree
Get the current state of the viewer layer tree.
Returns OMTreeNode The layer tree root node.
setNodeVisible
Set a layer tree node visible or invisible.
Parameters
visible
bool The group/layer visibility.recursive
bool If true, also set the visibility of layers within subgroups of the group node. If false, visibility will be applied to the direct layer children of the group node. (optional, defaulttrue
)
Returns void
hideLayerInLayerTree
Show or hide a layer for the user in the layer tree component. This only hides a layer in the user interface. The layer itself is still present in the map.
Parameters
layerId
string The id of the layer to show/hide.hidden
bool Set to true to hide the layer in the layer tree.
Returns void
OMTreeNode
A layer tree node from the response of OMTree.getLayerTree().
Properties
isGroup
bool True if the node is a group node.multiple
bool For group nodes, true if the layer group may have more than one visible layer.visible
bool For layer nodes, true if the layer is visible.children
Array<OMTreeNode> Child nodes. Only present within group nodes.
OMGeolocation
Class that wraps native geolocation functionality. Do not instantiate this class directly. A OMGeolocation instance is provided on api.geolocation after initializing a viewer.
getCurrentLocation
Get the current location. Returns a promise that will resolve with a OMGeolocationResult if a location can be determined. This is a plain object representation of a https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition.
Returns Promise<OMGeolocationResult> Promise that resolves with a geolocation result.
zoomToCurrentLocation
Zoom to current location (with optional zoom level parameter).
Parameters
zoom
number? Optional zoom level to zoom to. Defaults to 14.
Returns void
startWatch
Start geolocation watch mode. In watch mode, a marker is displayed on the map corresponding to the current GPS location.
Parameters
-
options
object? Options.
Returns void
clearWatch
Clear geolocation watch mode.
Returns void
OMGeoPosition
An object describing a geolocation position. This is a plain object wrapper for https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates.
Properties
latitude
number Latitude in decimal degrees.longitude
number Longitude in decimal degrees.altitude
number Altitude in meters, relative to sea level.accuracy
number Position accuracy in meters.altitudeAccuracy
number Altitude accuracy in meters.heading
number Heading angle in degrees clockwise starting from the north.speed
number Velocity in meters per second.
OMGeolocationResult
An object describing a geolocation result. This is a plain object wrapper for https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition.
Properties
coords
OMGeoPosition Geolocation coordinates.timestamp
number Creation time of geolocation result as timestamp with milisecond precision.
OMEdit
An object for managing protocols that manage transactions for saving edits. Do not instantiate this class directly. A OMEdit instance is provided on api.edit after initializing a viewer.
registerSaveProtocol
Register a save protocol for a layer. This save protocol is a function that accepts three parameters (inserts, updates, deletes), and returns a promise that resolves when the transaction was a success, and fails with a javascript Error instance detailing what went wrong when a transaction fails.
Explanation of save protocol parameters:
- inserts: an array of GeoJSON features to insert into the layer data store.
- updates: an array of GeoJSON features with a valid id.
The layer’s data store is updated with values and geometries for each feature in the updates array.
- deletes: an array of feature ids (string) to delete from the layer data store.
Parameters
layerId
string The id of the layer managed by the save protocol.protocol
Function The id of the layer managed by the save protocol.
Returns void
getSaveProtocol
Get the registered save protocol for a layer.
Parameters
layerId
string The id of the layer managed by the save protocol.
Returns Function protocol The id of the layer managed by the save protocol.
setFormOverride
Register an edit form override function for a layer. This function will be called whenever an edit form would be opened for the layer. This function receives an object with these parameters:
- layerId: the id of the layer being edited.
- featureIds: an array with ids of the features being edited, or null if a new feature is being created.
- formData: an object with the edited feature properties. A default object will be created for new features.
- jsonSchema: the json schema for the edit form.
- uiSchema: the ui schema for the edit form.
- saveChanges: a function that can be called to save any updated values. Only keys present in the changeset will be updated. Pass null to the function to cancel the edit in the viewer.
Parameters
layerId
string The id of the layer for which to override the edit form. Use ‘*’ to register a handler for all edit forms. Any form override registered with a specific layer id will take precedence over any handler registered with ‘*’.onFormOpen
Function The function to call when the edit form for a layer is opened.
Returns void
layerId
Get the edit form override function for a layer.
Parameters
layerId
string The id of the layer.
Returns Function The form override handler. Returns the function registered with ‘*’ (if any), if no layer-specific function has been registered. Any form override registered with a specific layer id will take precedence over any handler registered with ‘*’. Returns null if no override has been found.
setSnapLayer
Pick a single vector layer to snap to. Pass null as layerId to disable snapping in the map.
Parameters
snapLayerId
string Id of vector layer.
Returns void
setSnapActive
Enable or disable snapping for a vector layer.
Parameters
snapLayerId
string Id of vector layer.snapActive
bool? Set to true to enable snapping for a vector layer. Set to false to disable snapping.
Returns void
setEditLayer
Set a layer for editing. Use this method if there’s more than one editable layer in the map. This method will throw if the layer is not user-editable.
Parameters
layerId
string The id of the edit layer. Pass null to reset
Returns void
activateEditTool
Activate a specific edit tool (one of “EDIT_MODIFY_ATTRIBUTES”, “EDIT_MODIFY_GEOMETRY”, “EDIT_CREATE_POINT”, “EDIT_CREATE_LINE”, “EDIT_CREATE_POLYGON”). This method requires an active edit layer. Use the setEditLayer method to pick the active edit layer before calling this function.
Parameters
editMode
string One of “EDIT_MODIFY_ATTRIBUTES”, “EDIT_MODIFY_GEOMETRY”, “EDIT_CREATE_POINT”, “EDIT_CREATE_LINE”, “EDIT_CREATE_POLYGON”.
Returns void
deactivateEditTool
Deactivate any active edit tool.
Returns void
saveUserModifiedGeometries
Save all user-modified geometries. Only changes made by the ‘modify geometry’ tool are tracked and saved when calling this method.
Returns void
OMUtils
An object containing various utility functions for working with GeoJSON features and geometries. Do not instantiate this class directly. A OMUtils instance is provided on api.utils after initializing a viewer.
transformCoordinate
Transform an array of [x,y] coordinates to another projection. Returns a new array.
Parameters
coordinates
Array<number> Input coordinates as [x, y] array.sourceSrid
string Source projection SRID.destSrid
string Destination projection SRID.
Returns Array<number> The transformed coordinates.
transformGeometry
Transform a GeoJSON geometry to another projection. Returns a new geometry.
Parameters
geometry
GeoJSONGeometry Input GeoJSON geometry.sourceSrid
string Source projection SRID.destSrid
string Destination projection SRID.
Returns GeoJSONGeometry The transformed geometry.
transformFeature
Transform a GeoJSON feature to another projection. Returns a new feature with the same properties except a transformed version of the geometry.
Parameters
feature
GeoJSONFeature Input GeoJSON feature.sourceSrid
string Source projection SRID.destSrid
string Destination projection SRID.
Returns GeoJSONFeature The transformed feature.
calculateFeatureExtent
Calculate the extent of a GeoJSON feature.
Parameters
feature
GeoJSONFeature Input GeoJSON feature.
Returns Array<number> The feature extent as [xmin, ymin, xmax, ymax].
parseCqlFilter
Parse a CQL filter string expression into a filter object useable by Onemap.
Parameters
cqlFilter
string CQL filter string.
Returns object Filter object that can be used by Onemap.
OMInfoLinks
An object for managing functions that can fetch additional information for a single feature. Do not instantiate this class directly. An OMInfoLinnks instance is provided on api.edit after initializing a viewer.
registerInfoLink
Register an info link for a layer. An info link is an object with the following parameters:
- id: the id of the info link.
- title: the title of the info link.
- fetchInfoFunction: a function that accepts a GeoJSON feature and outputs a Promise that resolves to a string containing additional information for the given feature.
Parameters
layerId
string The layer id.infoLinkId
string The info link id.title
string The info link title.fetchInfoFunction
Function A function GeoJSONFeature => Promisethat fetches and templates additional information for a given feature. cached
bool Default true. When true, cache API response on a per-feature basis..
Returns void
getInfoLink
Get a registered info link for a layer.
Parameters
Returns object The info link object for the layer, with {id, title, fetchInfo} properties.
clearInfoLinks
Clear all registered info links for a layer.
Parameters
layerId
string The id of the layer.
Returns void
OMSearchEngines
An object for managing functions that can fetch additional information for a single feature. Do not instantiate this class directly. An OMSearchEngines instance is provided on api.search after initializing a viewer.
registerSearchEngine
Register a search engine. This is an object with the following parameters:
- id: the id of the search engine.
- title: the title of the search engine.
- search: a function that accepts a constraint and outputs a Promise
that resolves to a GeoJSON feature collection containing features matching the constraint. Passing a null constraint gets all features (up to a certain limit).
Parameters
searchEngineId
string The search engine id.title
string The search engine title.searchFunction
Function A function OMFilter => Promisethat fetches metadata
object? Optional metadata to store with the search engine, like layer id if the search engine is based on a (WFS) layer. features as a GeoJSON feature collection using the given constraint (which may be null == get all features).
Returns void
getSearchEngine
Get a registered search engine.
Parameters
searchEngineId
string The search engine id.
Returns object The search engine object, with {id, title, layerId, search} properties.
getSearchEngine
Get all registered search engines.
Returns Array<OMSearchEngine> An array of all registered search engines.
OMFeatureInfo
An object containing various utility functions for working feature info requests in the map. Do not instantiate this class directly. An OMFeatureInfo instance is provided on api.featureInfo after initializing a viewer.
showFeatureInfoByFeatureIds
Show templated feature info in the viewer for a given set of features, referenced by featureId. This method only works for layers that have a getFeature method. If feature info is configured to be displayed in a popup, the centre of all requested features is used.
Parameters
getFeatureInfoXY
Perform a feature info request on the map.
Parameters
xy
Array<number> The feature info coördinate in map projection.-
options
object? Feature info request options.options.silent
bool If true, suppress sending featureInfo Onemap events. Default false. (optional, defaultfalse
)options.showInViewer
bool If true, show feature info in viewer. Default true. (optional, defaulttrue
)options.layerIds
Array<string> Optional array of layer id’s to query. When not provided, all layers with info configured that are visible in the viewer will be queried.Note: vector layers need to be visible in the viewer to be able to query for feature info, since they use canvas pixel hit detection. WMS layers can be queried when not visible in the viewer.
Returns Promise<object> A promise that will resolve with null if there are no results, or an object containing the feature info results (and errors, if any). This object has two properties (same as the featureInfo.received event object):* results: An array of feature info results, one result per feature near the feature info request location.
- errors: An array of error objects for each layer that gave an error when attempting to get feature info.
clear
Clear any open feature info displays in the viewer.
Returns void
setShowOnHoverInfo
Register a function to determine if feature info should be shown on hover. This function will receive a GeoJSON feature and must return a boolean to indicate if on-hover info can be shown for this feature. This only applies if the layer has on-hover feature info configured.
Parameters
layerId
string Id of the layer for which the ‘show on hover’ function will be applied.showOnHoverInfo
Function A function that receives a GeoJSON feature and must return true if feature info should be shown for that feature.
Returns void
getShowOnHoverInfo
Get the function registered with setShowOnHoverInfo.
Parameters
layerId
string Id of the layer for which a ‘show on hover’ has been registered.
Returns Function The registered showOnHover function, or null if none has been registered.
OMFilter
The structure of the filter description is modeled after filter operators, see also geoserver.
An OMFilter is closely based on the OGC filter specification, with a few additions.
Properties
type
string Can be one of ‘comparison’, ‘and’, ‘or’, not’.operator
string? Required for type=’comparison’.Can be one of ‘propertyisequalto’, ‘propertyisnotequalto’, ‘propertyislessthan’, ‘propertyislessthanorequalto’, ‘propertyisgreaterthan’, ‘propertyisgreaterthanorequalto’, ‘propertyislike’, ‘propertyisbetween’, ‘propertyisnull’, ‘propertyinlist’predicate
OMFilter? Required for type=’not’. A single predicate to negate.predicates
Array<OMFilter>? Required for type=’and’ or type=’or’. An array of filter predicates that must all evaluate to true for ‘and’, or for which at least one must evaluate to true for ‘or’.propertyname
string? Required for type=’comparison’.literal
literal? A literal value (string or number) to use in a comparison, required for type=’comparison’, except when operator=’propertyisnull’.literals
Array<literal>? Array of literal values (string or number), used together with operator ‘propertyinlist’.lowerboundary
literal? Lower boundary, required for operator=’propertyisbetween’.upperboundary
literal? Upper boundary, required for operator=’propertyisbetween’.wildcard
string? Wildcard character for operator=’propertyislike’. Default is ‘*’.singlechar
string? Single char match character for operator=’propertyislike’. Default is ‘.’.escapechar
string? Escape character for operator=’propertyislike’. Default is ‘!’.matchcase
boolean? Use case sensitive matching for strings. Default true. Does not work for propertyisbetween or propertyisnull.