Viewer API version v5.20.0
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
initialAppConfigObject The viewer configuration object obtained from the Onemap backend.containerElementHTMLElement A DOM-node that will host the Onemap viewer.-
optionsobject Options. (optional, default{})options.customMessagesobject? 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.moveTolerancenumber? 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.forceMobileLayoutboolean? Force mobile layout. When true, the viewer will always use the mobile device layout, even for fullscreen and embedded viewers. Default false.options.allowInlineStylesboolean? 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.useNativeSelectboolean? When true, use native html select input component. Default false.options.applyOffsetCorrectionboolean? 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.enableScrollZoomboolean? Set to true to enable zoom on mouse scroll. This is disabled by default for embedded maps.options.mapParamsobject? Optional map parameters to merge into existing map parameters on init.options.snapshotobject? 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
urlstring The app root url. Defaults to ‘/’.
Returns void
setJwtToken
Set the JWT token used to call Onemap endpoints that require authorization.
Parameters
jwtTokenstring 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
urlstring 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
eventsOMEvents 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
paramsobject 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
eventNamestring The event to listen for, or ‘*’ to listen to any event.eventHandlerfunction 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
eventNamestring The event to listen for, or ‘*’ to listen to any event.eventHandlerfunction 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
layerIdstring The id of the layer containing the feature.featureIdstring The id of the feature.propertiesobject The raw properties of the feature.htmlstring The templated feature info.geometryGeoJSONGeometry The feature geometry as GeoJSON geometry.
FeatureInfoError
Feature info for a single feature.
Type: object
Properties
FeatureInfoSlide
Feature info slide properties.
Type: object
Properties
indexnumber The currently visible slide index.layerIdstring The id of the layer containing the feature.featureIdstring The id of the feature corresponding to the visible slide.propertiesobject The raw properties of the feature.geometryGeoJSONGeometry 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
resultsArray<FeatureInfoResult> An array of feature info results, one result per feature near the feature info request location.errorsArray<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
currentSlideFeatureInfoSlide 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).
search.resultsReceived
Emitted after search results have been obtained.
Type: object
Properties
resultsGeoJSONFeatureCollection Results found as GeoJSON feature collection in CRS:84 projection.searchEngineIdstring ID of search engine that executed the search.
edit.transactionStarted
Emitted when edit transaction starts for a layer.
Type: object
Properties
layerIdstring Layer id.
edit.transactionSuccess
Emitted after edit transaction succeeds for a layer.
Type: object
Properties
layerIdstring 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
layerIdstring Layer id.featuresArray<GeoJSONFeature> An array of GeoJSON features that have been inserted.
edit.featureGeometryUpdated
Emitted after a feature geometry has been successfully updated.
Type: object
Properties
layerIdstring Layer id.featureIdstring Id of the feature to update.geometryGeoJSONGeometry The new geometry as GeoJSON geometry.
edit.featurePropertiesUpdated
Emitted after feature properties have been successfully updated.
Type: object
Properties
layerIdstring Layer id.featureIdstring Id of the feature to update.propertiesobject New feature properties. Contains only properties that were updated.
edit.featuresDeleted
Emitted after features are deleted from a layer.
Type: object
Properties
layerIdstring Layer id.featureIdsArray<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
rotationnumber 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
coordinateArray<number> The map click coordinate in map projection.lonlatArray<number> Map click coordinate in CRS:84 as [lon, lat].layersArray<string> Array containing id’s of layers hit by map click.
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
hitsobject 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
centerArray<number> The map center as [x, y] in map projection.zoomnumber The zoom level.resolutionnumber The map resolution.rotationnumber The map rotation in radians in clockwise direction.
layer.loadStart
Emitted when a layer starts loading data.
Type: object
Properties
layerIdstring The layer id.
layer.loadEnd
Emitted when all data has been loaded for a layer.
Type: object
Properties
layerIdstring 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
layerIdstring The layer id.visibilitybool 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
featureobject 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
featureobject The modified feature as GeoJSON feature.
sketch.error
Emitted when the user draws an invalid sketch geometry.
Type: object
Properties
messagestring 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
coordinatesArray<Number> The coordinates of the new vertex.selfClosingPointbool 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
featureobject The measure as GeoJSON feature.
measure.error
Emitted when the user draws an invalid measure geometry.
Type: object
Properties
messagestring 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
-
queryobject The search query parameters. -
searchEnginestring? One of ‘pdoklocator’ (default) or ‘geopuntportal’.
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
-
queryobject The search query parameters. -
searchEnginestring? One of ‘pdoklocator’ (default) or ‘geopuntportal’.
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
coordinateArray<number> Input coordinate in CRS:84 as [lon, lat].searchEnginestring? One of ‘pdoklocator’ (default) or ‘geopuntportal’.
Returns Promise<ReverseGeocodeResult> A promise that resolves with the reverse geocoding result.
AutocompleteSuggestion
OMSearch autocomplete suggestion result.
Type: Object
Properties
valueany Search result value.labelstring Search result display label as text.formattedLabelstring? If the search engine supports it, formattedLabellocatorTypestring Type of locator used to retrieve the autocomplete suggestion. contains the search result formatted as HTML with matching parts highlighted.
ReverseGeocodeResult
OMSearch reverse geocode result.
Type: Object
Properties
formattedLocationstring Location description as formatted string.dataobject? Optional object with properties describing the location.geometryobject? 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
extentArray<number> Bounds array: [left, bottom, right, top].-
optionsobject 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
featureCollectionGeoJSONFeatureCollection GeoJSON feature collection.-
optionsobject Extra options for zooming to extent. (optional, default{})
Returns void
zoomToSelection
Zoom to the extent of all selected features.
Parameters
-
optionsobject Extra options for zooming to extent. (optional, default{})options.maxZoomnumber? 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
layerOMLayer A Onemap layer wrapper.-
optionsobject Options. (optional, default{})options.maxZoomnumber? Max zoom level. Useful when the layer contains a single feature.
Returns void
setCenter
Reposition the map to a new center.
Parameters
centerArray<number> Center as [x, y].-
optionsobject Extra options for zooming to extent. Note: zoom result may be restricted by map settings. (optional, default{})options.sridstring? The spatial reference id of the given center, e.g. ‘EPSG:4326’. If no SRID is given, the map SRID is assumed.options.zoomnumber? The zoom level to set on the map. When given the map zoom is set as wel as the new center.options.zoomRadiusMnumber? 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
rotationnumber 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
activebool 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
layerIdstring 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
titleOrNamestring 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.
addSourcelessLayer
Add a sourceless layer to the map.
Parameters
idstring Layer id. Cannot use the id of a layer already present.titlestring Layer title.-
optionsobject Optional layer properties. (optional, default{})options.visibleInViewerTreebool? Add layer to layer tree in viewer. Default true.options.featureInfoClickTemplatestring? Template for on-click feature info. Activates on-click feature info when given.options.featureInfoHoverTemplatestring? Template for on-hover feature info. Activates on-hover feature info when given.options.sldstring? SLD style document. Layer uses default styling when SLD is not given.
Returns Promise<OMLayer> A promise that resolves with an OMLayer instance once the layer is added and ready for use.
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
snapshotobject 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
sketchModestring One of Point, LineString, Polygon, Circle, or Box.-
optionsobject Sketch options.options.clearPreviousboolean When true, previous sketches with the same category are cleared after finishing a new one. Default true.options.stopAfterSketchboolean When true, sketch.stop() is called automatically after finishing a sketch. Default false.options.addSketchToMapboolean When true, the sketch is added to the map after firing the sketchComplete event. Default true.options.categorystring When added to the map, features will get this category tag. Default value ‘sketchDefault’.options.freehandbool When true, drawing operates in freehand mode. Does nothing for mode Point or Circle. Default false.options.toolActionstring 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
categorystring? 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
featuresobject A GeoJSON feature collection.-
optionsobject Options.options.sridstring SRS identifier string of source data projection. When not given, CRS:84 is assumed as per GeoJSON specification.options.sourceSridstring deprecated Same as srid, but will be deprecated in a later version. Use options.srid instead.options.categorystring Sketch category. Default value is ‘sketchDefault’.
Returns void
getFeatures
Get sketch features as GeoJSON feature collection.
Parameters
-
optionsobject? Options. (optional, default{})options.sridstring? Transform sketch features to this projection. By default, sketch features are returned in map projection. Use “CRS:84” to obtain sketches in lon/lat.
Returns GeoJSONFeatureCollection GeoJSON feature collection of all sketch features in map projection.
getFeatureById
Get sketch feature by ID.
Parameters
featureIdstring 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
updateFeatureGeoJSONFeature The update feature.
Returns void
deleteFeature
Remove a single sketch feature by id.
Parameters
featureIdstring 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
queryGeometryGeoJSONGeometry Query geometry in map projection.-
optionsobject Options.options.withinboolean? If true, only select features entirely within the given geometry. Default false.
Returns void
SketchStyleProps
Sketch style properties.
Type: object
Parameters
strokeWidthnumber Stroke width in css pixels.strokeColorstring Stroke color as #ABCDEF hex string.strokeOpacitynumber Stroke opacity (number between 0 and 1).fillColorstring Fill color as #ABCDEF hex string.fillOpacitynumber Fill opacity (number between 0 and 1).pointRadiusnumber 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
idstring The Onemap layer id.titlestring The layer title.namestring The layer name as advertised in the capabilitites document of the layer’s service.serviceTypestring Layer service type.identifierFieldsArray<string> An array of field names that identify features in the layer.fieldsobject 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.geometryFieldNamestring 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
-
optionsobject Options.options.sridstring? 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.bboxArray<number>? When given, only return features whose bbox intersects the given bbox. Bbox projection must equal the map projection.options.queryGeometryGeoJSONGeometry? 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.withinbool? 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
featureIdstring The id of the feature.-
optionsobject Options.options.sridstring 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.
getTileMatrixSet
Gets the tile matrix set used by a WMTS layer in the viewer. This function will return null if the layer is not a WMTS layer.
Returns object A WMTS tile matrix set.
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
loadGeoJSONFeatures
Loads features from layer source as GeoJSON. If the source does not have a loader, this method property will be undefined.
Parameters
bboxArray<number> The bbox used in the GetFeatures request. Set this to null to request features without bbox.-
optionsobject Loader options.options.sridstring 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.filterOMFilter An optional filter used to load the features. This filter will be combined with the bbox parameter, if any is provided.options.onPageLoadFunction Optional callback that will be called with a feature collection for each loaded page.options.discardOutputbool If set to true, do not add loaded features to output. To be used together with an onPageLoad callback.
Returns Promise<GeoJSONFeatureCollection> A promise that resolves with the loaded features as GeoJSON feature collection.
loadGeoJSONFeatures
[DEPRECATED, use layer.loadGeoJSONFeatures instead]
Loads features from WFS layer source as GeoJSON. If the source does not have a WFS loader, this method property will be undefined.
Parameters
bboxArray<number> The bbox used in the GetFeatures request. Set this to null to request features without bbox.-
optionsobject Loader options.options.sridstring 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.filterOMFilter An optional filter used to load the features. This filter will be combined with the bbox parameter, if any is provided.
Returns Promise<GeoJSONFeatureCollection> A promise that resolves with the loaded features as GeoJSON feature collection.
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
visiblebool 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 can be an SLD XML string or a Onemap style:
{strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity, pointRadius}.
Parameters
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
opacitydouble The new layer opacity as a number between 0 and 1.
Returns OMLayer The OMLayer instance.
setSwipe
Change swipe status for a layer to ‘left’, ‘right’, or null. If the map has any layer with non-null swipe status, a draggable swipe bar will appear on the map. Layers with swipe status ‘left’ will be displayed on the left of the swipe bar. Similarly for status ‘right’. Set swipe status to null to reset swipe for a layer.
Parameters
swipestring Set to ‘left’, ‘right’, or null.
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
filterOMFilter 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
-
optionsobject Options.options.sridstring 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
omFilterOMFilter 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
-
optionsobject Options. (optional, default{})options.maxZoomnumber? 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
-
optionsobject Options. (optional, default{})options.maxZoomnumber? 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
geometryGeoJSONGeometry GeoJSON geometry. Coordinates must be in map projection.-
optionsobject Options.options.withinboolean? 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
geometryGeoJSONGeometry GeoJSON geometry. Coordinates must be in map projection.-
optionsobject Options.options.withinboolean? 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
idstring 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
insertsArray<GeoJSONFeature> An array of GeoJSON features to insert. The coordinates have to be in the layer’s default projection.updatesArray<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.deletesArray<string> An array of feature ids to delete.-
optionsobject Transaction options. (optional, default{})options.resumeOnTransactionErrorboolean? Default false. If true, treat a failed transaction as success. This unblocks the layer from performing another transaction.options.reloadAfterEditboolean? 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.deselectAfterSavebool 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
geometryGeoJSONGeometry 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.
findTreeNodesByTitle
Finds all map tree nodes that have the given title.
Parameters
titlestring Node title.
Returns Array<OMTreeNode> Array of tree nodes with the given title.
setNodeVisible
Set a layer tree node visible or invisible.
Parameters
visiblebool The group/layer visibility.recursivebool 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
layerIdstring The id of the layer to show/hide.hiddenbool 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
titlestring Title of group or layer node.isGroupbool True if the node is a group node.multiplebool For group nodes, true if the layer group may have more than one visible layer.visiblebool For layer nodes, true if the layer is visible.childrenArray<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
zoomnumber? 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
-
optionsobject? Options.
Returns void
clearWatch
Clear geolocation watch mode.
Returns void
toggleFollow
Toggle geolocation follow mode. When follow mode is on, the map will center itself on the GPS position.
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
latitudenumber Latitude in decimal degrees.longitudenumber Longitude in decimal degrees.altitudenumber Altitude in meters, relative to sea level.accuracynumber Position accuracy in meters.altitudeAccuracynumber Altitude accuracy in meters.headingnumber Heading angle in degrees clockwise starting from the north.speednumber 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
coordsOMGeoPosition Geolocation coordinates.timestampnumber 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
layerIdstring The id of the layer managed by the save protocol.protocolFunction The id of the layer managed by the save protocol.
Returns void
getSaveProtocol
Get the registered save protocol for a layer.
Parameters
layerIdstring 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.
- groups: optional. An array that groups fields into tabs: [{ title: string, fields: string[] }]. The fields array contains the names of the fields for each tab. This property can be null. In that case, show the default form containing all fields.
- 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
layerIdstring 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 ‘*’.onFormOpenFunction 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
layerIdstring 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
snapLayerIdstring Id of vector layer.
Returns void
setSnapActive
Enable or disable snapping for a vector layer.
Parameters
snapLayerIdstring Id of vector layer.snapActivebool? 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
layerIdstring 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
editModestring 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. An OMUtils instance is also available at the global level as om.utils.
transformCoordinate
Transform an array of [x,y] coordinates to another projection. Returns a new array.
Parameters
coordinatesArray<number> Input coordinates as [x, y] array.sourceSridstring Source projection SRID.destSridstring Destination projection SRID.
Returns Array<number> The transformed coordinates.
transformGeometry
Transform a GeoJSON geometry to another projection. Returns a new geometry.
Parameters
geometryGeoJSONGeometry Input GeoJSON geometry.sourceSridstring Source projection SRID.destSridstring 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
featureGeoJSONFeature Input GeoJSON feature.sourceSridstring Source projection SRID.destSridstring Destination projection SRID.
Returns GeoJSONFeature The transformed feature.
calculateFeatureExtent
Calculate the extent of a GeoJSON feature.
Parameters
featureGeoJSONFeature 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
cqlFilterstring CQL filter string.
Returns object Filter object that can be used by Onemap.
writeSqliteWhereClause
Convert a Onemap filter into a parameterized where clause for use in SQLite.
Parameters
omFilterOMFilter Onemap filter object.
Returns object Parameterized filter: { whereClause, parameters }, with whereClause a string representing a parameterized SQLite where clause, and parameters an array with parameter values represented by ? in the where clause.
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
layerIdstring The layer id.infoLinkIdstring The info link id.titlestring The info link title.fetchInfoFunctionFunction A function GeoJSONFeature => Promisethat fetches and templates additional information for a given feature. cachedbool 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
layerIdstring 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
searchEngineIdstring The search engine id.titlestring The search engine title.searchFunctionFunction A function OMFilter => Promisethat fetches metadataobject? 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
searchEngineIdstring 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
xyArray<number> The feature info coördinate in map projection.-
optionsobject? Feature info request options.options.silentbool If true, suppress sending featureInfo Onemap events. Default false. (optional, defaultfalse)options.showInViewerbool If true, show feature info in viewer. Default true. (optional, defaulttrue)options.layerIdsArray<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
layerIdstring Id of the layer for which the ‘show on hover’ function will be applied.showOnHoverInfoFunction 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
layerIdstring 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
typestring Can be one of ‘comparison’, ‘and’, ‘or’, not’.operatorstring? Required for type=’comparison’.Can be one of ‘propertyisequalto’, ‘propertyisnotequalto’, ‘propertyislessthan’, ‘propertyislessthanorequalto’, ‘propertyisgreaterthan’, ‘propertyisgreaterthanorequalto’, ‘propertyislike’, ‘propertyisbetween’, ‘propertyisnull’, ‘propertyinlist’predicateOMFilter? Required for type=’not’. A single predicate to negate.predicatesArray<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’.propertynamestring? Required for type=’comparison’.literalliteral? A literal value (string or number) to use in a comparison, required for type=’comparison’, except when operator=’propertyisnull’.literalsArray<literal>? Array of literal values (string or number), used together with operator ‘propertyinlist’.lowerboundaryliteral? Lower boundary, required for operator=’propertyisbetween’.upperboundaryliteral? Upper boundary, required for operator=’propertyisbetween’.wildcardstring? Wildcard character for operator=’propertyislike’. Default is ‘*’.singlecharstring? Single char match character for operator=’propertyislike’. Default is ‘.’.escapecharstring? Escape character for operator=’propertyislike’. Default is ‘!’.matchcaseboolean? Use case sensitive matching for strings. Default true. Does not work for propertyisbetween or propertyisnull.