Class: VectorSource

ol/source/Vector~VectorSource


import VectorSource from 'ol/source/Vector';

Provides a source of features for vector layers. Vector features provided by this source are suitable for editing. See VectorTile for vector data that is optimized for rendering.

new VectorSource(options)

Name Type Description
attributions AttributionLike | undefined

Attributions.

features Array<Feature> | Collection<Feature> | undefined

Features. If provided as Collection, the features in the source and the collection will stay in sync.

format FeatureFormat | undefined

The feature format used by the XHR feature loader when url is set. Required if url is set, otherwise ignored.

loader FeatureLoader | undefined

The loader function used to load features, from a remote source for example. If this is not set and url is set, the source will create and use an XHR feature loader. The 'featuresloadend' and 'featuresloaderror' events will only fire if the success and failure callbacks are used.

Example:

import {Vector} from 'ol/source';
import {GeoJSON} from 'ol/format';
import {bbox} from 'ol/loadingstrategy';

const vectorSource = new Vector({
  format: new GeoJSON(),
  loader: function(extent, resolution, projection, success, failure) {
     const proj = projection.getCode();
     const url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
         'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
         'outputFormat=application/json&srsname=' + proj + '&' +
         'bbox=' + extent.join(',') + ',' + proj;
     const xhr = new XMLHttpRequest();
     xhr.open('GET', url);
     const onError = function() {
       vectorSource.removeLoadedExtent(extent);
       failure();
     }
     xhr.onerror = onError;
     xhr.onload = function() {
       if (xhr.status == 200) {
         const features = vectorSource.getFormat().readFeatures(xhr.responseText);
         vectorSource.addFeatures(features);
         success(features);
       } else {
         onError();
       }
     }
     xhr.send();
   },
   strategy: bbox,
 });
overlaps boolean (defaults to true)

This source may have overlapping geometries. Setting this to false (e.g. for sources with polygons that represent administrative boundaries or TopoJSON sources) allows the renderer to optimise fill and stroke operations.

strategy LoadingStrategy | undefined

The loading strategy to use. By default an all strategy is used, a one-off strategy which loads all features at once.

url string | FeatureUrlFunction | undefined

Setting this option instructs the source to load features using an XHR loader (see xhr). Use a string and an all for a one-off download of all features from the given URL. Use a FeatureUrlFunction to generate the url with other loading strategies. Requires format to be set as well. When default XHR feature loader is provided, the features will be transformed from the data projection to the view projection during parsing. If your remote data source does not advertise its projection properly, this transformation will be incorrect. For some formats, the default projection (usually EPSG:4326) can be overridden by setting the dataProjection constructor option on the format. Note that if a source contains non-feature data, such as a GeoJSON geometry or a KML NetworkLink, these will be ignored. Use a custom loader to load these.

useSpatialIndex boolean (defaults to true)

By default, an RTree is used as spatial index. When features are removed and added frequently, and the total number of features is low, setting this to false may improve performance.

Note that getFeaturesInExtent, getClosestFeatureToCoordinate and getExtent cannot be used when useSpatialIndex is set to false, and forEachFeatureInExtent will loop through all features.

When set to false, the features will be maintained in an Collection, which can be retrieved through getFeaturesCollection.

wrapX boolean (defaults to true)

Wrap the world horizontally. For vector editing across the -180° and 180° meridians to work properly, this should be set to false. The resulting geometry coordinates will then exceed the world bounds.

Fires:

Subclasses

Extends

Methods

addFeature(feature)

Add a single feature to the source. If you want to add a batch of features at once, call #addFeatures() instead. A feature will not be added to the source if feature with the same id is already there. The reason for this behavior is to avoid feature duplication when using bbox or tile loading strategies. Note: this also applies if an Collection is used for features, meaning that if a feature with a duplicate id is added in the collection, it will be removed from it right away.

Name Type Description
feature Feature

Feature to add.

addFeatures(features)

Add a batch of features to the source.

Name Type Description
features Array<Feature>

Features to add.

Increases the revision counter and dispatches a 'change' event.

clear(fast)

Remove all features from the source.

Name Type Description
fast boolean | undefined

Skip dispatching of removefeature events.

dispatchEvent(event){boolean | undefined} inherited

Dispatches an event and calls all listeners listening for events of this type. The event parameter can either be a string or an Object with a type property.

Name Type Description
event BaseEvent | string

Event object.

Returns:
false if anyone called preventDefault on the event object or if any of the listeners returned false.

forEachFeature(callback){T | undefined}

Iterate through all features on the source, calling the provided callback with each one. If the callback returns any "truthy" value, iteration will stop and the function will return the same value. Note: this function only iterate through the feature that have a defined geometry.

Name Type Description
callback function

Called with each feature on the source. Return a truthy value to stop iteration.

Returns:
The return value from the last call to the callback.

forEachFeatureInExtent(extent, callback){T | undefined}

Iterate through all features whose bounding box intersects the provided extent (note that the feature's geometry may not intersect the extent), calling the callback with each feature. If the callback returns a "truthy" value, iteration will stop and the function will return the same value.

If you are interested in features whose geometry intersects an extent, call the #forEachFeatureIntersectingExtent() method instead.

When useSpatialIndex is set to false, this method will loop through all features, equivalent to #forEachFeature().

Name Type Description
extent Extent

Extent.

callback function

Called with each feature whose bounding box intersects the provided extent.

Returns:
The return value from the last call to the callback.

forEachFeatureIntersectingExtent(extent, callback){T | undefined}

Iterate through all features whose geometry intersects the provided extent, calling the callback with each feature. If the callback returns a "truthy" value, iteration will stop and the function will return the same value.

If you only want to test for bounding box intersection, call the #forEachFeatureInExtent() method instead.

Name Type Description
extent Extent

Extent.

callback function

Called with each feature whose geometry intersects the provided extent.

Returns:
The return value from the last call to the callback.

Gets a value.

Name Type Description
key string

Key name.

Returns:
Value.

Get the attribution function for the source.

Returns:
Attribution function.

getAttributionsCollapsible(){boolean} inherited

Returns:
Attributions are collapsible.

getClosestFeatureToCoordinate(coordinate, filter){Feature}

Get the closest feature to the provided coordinate.

This method is not available when the source is configured with useSpatialIndex set to false.

Name Type Description
coordinate Coordinate

Coordinate.

filter function | undefined

Feature filter function. The filter function will receive one argument, the feature and it should return a boolean value. By default, no filtering is made.

Returns:
Closest feature.

getExtent(extent){Extent}

Get the extent of the features currently in the source.

This method is not available when the source is configured with useSpatialIndex set to false.

Name Type Description
extent Extent | undefined

Destination extent. If provided, no new extent will be created. Instead, that extent's coordinates will be overwritten.

Returns:
Extent.

getFeatureById(id){Feature | null}

Get a feature by its identifier (the value returned by feature.getId()). Note that the index treats string and numeric identifiers as the same. So source.getFeatureById(2) will return a feature with id '2' or 2.

Name Type Description
id string | number

Feature identifier.

Returns:
The feature (or null if not found).

getFeatures(){Array<Feature>}

Get a snapshot of the features currently on the source in random order. The returned array is a copy, the features are references to the features in the source.

Returns:
Features.

getFeaturesAtCoordinate(coordinate){Array<Feature>}

Get all features whose geometry intersects the provided coordinate.

Name Type Description
coordinate Coordinate

Coordinate.

Returns:
Features.

getFeaturesCollection(){Collection<Feature> | null}

Get the features collection associated with this source. Will be null unless the source was configured with useSpatialIndex set to false, or with an Collection as features.

Returns:
The collection of features.

getFeaturesInExtent(extent, projection){Array<Feature>}

Get all features whose bounding box intersects the provided extent. Note that this returns an array of all features intersecting the given extent in random order (so it may include features whose geometries do not intersect the extent).

When useSpatialIndex is set to false, this method will return all features.

Name Type Description
extent Extent

Extent.

projection Projection | undefined

Include features where extent exceeds the x-axis bounds of projection and wraps around the world.

Returns:
Features.

getFormat(){FeatureFormat | undefined}

Get the format associated with this source.

Returns:
The feature format.

getKeys(){Array.<string>} inherited

Get a list of object property names.

Returns:
List of property names.

getProjection(){Projection | null} inherited

Get the projection of the source.

Returns:
Projection.

getProperties(){Object.<string, *>} inherited

Get an object of all property names and values.

Returns:
Object.

getRevision(){number} inherited

Get the version number for this object. Each time the object is modified, its version number will be incremented.

Returns:
Revision.

Get the state of the source, see State for possible states.

Returns:
State.

getUrl(){string | FeatureUrlFunction | undefined}

Get the url associated with this source.

Returns:
The url.

hasFeature(feature){boolean}

Returns true if the feature is contained within the source.

Name Type Description
feature Feature

Feature.

Returns:
Has feature.

on(type, listener){EventsKey | Array<EventsKey>} inherited

Listen for a certain type of event.

Name Type Description
type string | Array.<string>

The event type or array of event types.

listener function

The listener function.

Returns:
Unique key for the listener. If called with an array of event types as the first argument, the return will be an array of keys.

once(type, listener){EventsKey | Array<EventsKey>} inherited

Listen once for a certain type of event.

Name Type Description
type string | Array.<string>

The event type or array of event types.

listener function

The listener function.

Returns:
Unique key for the listener. If called with an array of event types as the first argument, the return will be an array of keys.

Refreshes the source. The source will be cleared, and data from the server will be reloaded.

removeFeature(feature)

Remove a single feature from the source. If you want to remove all features at once, use the #clear() method instead.

Name Type Description
feature Feature

Feature to remove.

removeLoadedExtent(extent)

Remove an extent from the list of loaded extents.

Name Type Description
extent Extent

Extent.

set(key, value, silent) inherited

Sets a value.

Name Type Description
key string

Key name.

value *

Value.

silent boolean | undefined

Update without triggering an event.

setAttributions(attributions) inherited

Set the attributions of the source.

Name Type Description
attributions AttributionLike | undefined

Attributions. Can be passed as string, Array<string>, Attribution, or undefined.

setLoader(loader)

Set the new loader of the source. The next render cycle will use the new loader.

Name Type Description
loader FeatureLoader

The loader to set.

setProperties(values, silent) inherited

Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties).

Name Type Description
values Object.<string, *>

Values.

silent boolean | undefined

Update without triggering an event.

Points the source to a new url. The next render cycle will use the new url.

Name Type Description
url string | FeatureUrlFunction

Url.

un(type, listener) inherited

Unlisten for a certain type of event.

Name Type Description
type string | Array.<string>

The event type or array of event types.

listener function

The listener function.

unset(key, silent) inherited

Unsets a property.

Name Type Description
key string

Key name.

silent boolean | undefined

Unset without triggering an event.