@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
74 lines (73 loc) • 3.07 kB
JavaScript
import LayerWms from '../../models/layers/layerwms.js';
import SelectionParam from '../../models/selectionparam.js';
import { removeUnwantedOlParams } from '../../tools/utils/olutils.js';
import { WKT } from 'ol/format.js';
import CsvManager from '../../tools/export/csvmanager.js';
import ColumnAliasHelper from '../../tools/utils/aliases.js';
class LayerCsvExporter {
context;
csvManager;
columnAliasHelper;
wktFormat = new WKT();
WKT_DECIMALS = 2;
csvContentTruncated = false;
constructor(context) {
this.context = context;
this.csvManager = new CsvManager(this.context);
this.columnAliasHelper = new ColumnAliasHelper(this.context.stateManager);
}
async createCsvFile(layer) {
this.csvContentTruncated = false;
if (!layer) {
return;
}
if (layer instanceof LayerWms) {
const features = await this.requestFeatures(layer);
const { data, columnDefs } = this.featuresToColumnData(features, layer.name);
const layerName = this.context.i18nManager.getTranslation(layer.name);
this.csvManager.startDownload(data, columnDefs, `${layerName}-filter-result.csv`);
}
}
async requestFeatures(layer) {
// Create a selection param object that defines the map max extent but nothing more.
// Any layer filter will be applied in the client automatically.
const projection = this.context.mapManager.getMap().getView().getProjection();
let extent = this.context.configManager.Config.map.maxExtent?.split(',').map(Number);
extent ??= projection.getExtent();
const selectionParam = new SelectionParam(layer.ogcServer, [layer], projection.getCode(), extent);
if (layer.wfsQueryable) {
const client = this.context.wfsManager.getClient(layer.ogcServer);
return await client.getFeature(selectionParam).then((features) => {
if (features.length === client.maxFeatures) {
this.csvContentTruncated = true;
}
return features;
});
}
else {
return [];
}
}
featuresToColumnData(features, layerName, includeGeometry = true) {
const data = features.map((feature) => {
const properties = removeUnwantedOlParams(feature, false);
const geometry = feature.getGeometry();
if (includeGeometry && geometry) {
properties[feature.getGeometryName()] = this.wktFormat.writeGeometry(geometry, {
decimals: this.WKT_DECIMALS
});
}
return properties;
});
let columnDefs = [];
if (data.length > 0) {
columnDefs = Object.keys(data[0]).map((columnName) => {
return {
name: this.columnAliasHelper.getColumnAlias(layerName, columnName)
};
});
}
return { data, columnDefs };
}
}
export default LayerCsvExporter;