@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
742 lines • 59.1 kB
JavaScript
import { html as uHtml } from 'uhtml';
import GirafeHTMLElement from '../../../base/GirafeHTMLElement.js';
import { CrossSectionState } from '../crosssectionstate.js';
import { download } from '../../../tools/export/download.js';
import { Circle, Icon, Fill, Stroke, Style, Text } from 'ol/style.js';
import VectorSource from 'ol/source/Vector.js';
import VectorLayer from 'ol/layer/Vector.js';
import Feature from 'ol/Feature.js';
import { LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryCollection } from 'ol/geom.js';
import { Draw, Modify } from 'ol/interaction.js';
import { KML, GeoJSON, GPX } from 'ol/format.js';
import { noModifierKeys, primaryAction } from 'ol/events/condition.js';
import OL3Parser from 'jsts/org/locationtech/jts/io/OL3Parser.js';
import { BufferOp, BufferParameters } from 'jsts/org/locationtech/jts/operation/buffer.js';
import { getDistance } from '../../../tools/utils/olutils.js';
class CrossSectionSettingsComponent extends GirafeHTMLElement {
templateUrl = null;
styleUrls = null;
template = () => {
return uHtml `<style>
#panel{min-width:25rem;height:100%;overflow:auto}#content{background:var(--bkg-color);margin:0;padding:1.5rem}#content .message{text-align:center;width:100%}#content .message *{margin:.25rem}#content div.option{justify-content:space-between;margin-top:.5rem;display:flex}h3,.text-label{color:var(--text-color)}.scrollable-table-container{width:100%;max-height:200px;display:block;overflow-y:auto}.scrollable-table{border-collapse:collapse;width:100%}.scrollable-table td{color:var(--text-color)}.table-cell{border:none;padding:4px 2px}.sticky-header{z-index:1;background-color:#f1f1f1;border:none;padding:5px 2px;position:sticky;top:0}.cell{flex:100px;min-width:100px;max-width:100%}input{background-color:var(--bkg-color);color:var(--text-color);border:solid 1px var(--text-color);border-radius:3px;outline:0}.btn-group{margin:5px 0}.btn-group-flex{flex-direction:row;gap:.5rem;margin:.5rem auto;display:flex}.btn-group-flex>button,.btn-group-flex>select,.btn-group-flex>input{width:50%}.btn-group-flex input.gg-checkbox{flex-grow:0;width:auto}.btn-group-flex>label{text-align:right;width:50%}.btn-group-flex label:after{content:" :"}.btn-group-inline{gap:5px;margin:10px auto;display:inline}.btn-group-grid{gap:5px;margin:10px auto;display:grid}.reset-btn{background-color:var(--bkg-color);width:22px;color:var(--text-color);border:none;border-radius:50%;justify-content:center;align-items:center;margin:2px;padding:0;display:flex}.reset-btn img{object-fit:contain}.reset-btn:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.action-btn{color:#fff;background-color:none;border-radius:50%;margin:2px;padding:2px}.action-btn:hover{background-color:var(--bkg-color-grad1);cursor:pointer;border-radius:50%}.dataset-row{box-sizing:border-box;border-bottom:1px solid #eee;align-items:center;gap:.5rem;width:100%;padding:.25rem 0;font-size:.875rem;line-height:1.2;display:flex}.dataset-row:last-child{border-bottom:none}.dataset-row>*{flex-shrink:0}.dataset-name{white-space:nowrap;text-overflow:ellipsis;min-width:6rem;color:var(--text-color);flex:auto;overflow:hidden}.icon-wrapper{justify-content:center;align-items:center;width:1.25rem;height:1.25rem;margin-right:.5rem;display:flex}.loader-progress{flex-direction:column;align-items:flex-start;width:100%}.progress-wrapper{width:100%;position:relative}.gg-progress{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:#eee;width:100%;height:1.95rem}.gg-progress::-webkit-progress-bar{background-color:#eee;border-radius:0}.gg-progress::-webkit-progress-value{background-color:#929292;border-radius:0}.gg-progress::-moz-progress-bar{background-color:#929292;border-radius:0}.progress-label{justify-content:center;align-items:center;font-size:.875rem;display:flex;position:absolute;inset:0}.progress-icon{pointer-events:none;mix-blend-mode:difference;position:absolute;left:.5em}
</style><style>
.hidden{display:none!important}.gg-rotate90{transform:rotate(90deg)}.gg-rotate180{transform:rotate(180deg)}.gg-rotate270{transform:rotate(270deg)}img{filter:var(--svg-filter)}img.legend-image{filter:var(--svg-map-filter);background:var(--svg-legend-bkg)}div{scrollbar-width:thin}a,a:visited{color:var(--link-color)}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}to{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-timing-function:linear;animation-iteration-count:infinite}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-timing-function:linear;animation-iteration-count:infinite}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}button,input,select,textarea{font:inherit}.gg-button,.gg-select,.gg-input,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);border:var(--app-standard-border);box-sizing:border-box;cursor:pointer;border-radius:3px;outline:0;margin:0;padding:0 0 0 .5rem;display:inline-block}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;align-items:center;margin:0;padding:0;display:flex}.gg-button,.gg-select,.gg-input,.gg-label{min-height:calc(var(--app-standard-height) / 1.5)}.gg-textarea{max-height:initial;resize:vertical;height:6rem;padding:.5rem;line-height:1.3rem}.gg-input{cursor:text}.gg-checkbox{accent-color:var(--text-color);width:1.2rem}.gg-range{accent-color:var(--text-color)}.gg-button{padding:0 .5rem}.gg-button.active{border:solid 1px var(--text-color-grad1);background-color:var(--bkg-color-grad2)}.gg-button:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed;border:none}.gg-button:disabled img{filter:opacity(.6)}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{color:var(--text-color);cursor:pointer;background-color:#0000;border:none;flex-direction:column;justify-content:center;align-items:center;padding:0;display:flex}.gg-icon{justify-content:center;align-items:center;display:flex}.gg-big,.gg-big-withtext{min-width:var(--app-standard-height);min-height:var(--app-standard-height);max-height:var(--app-standard-height)}.gg-big img,.gg-big-withtext img{width:calc(var(--app-standard-height) - 1.5rem);margin:0}.gg-big-withtext span{font-variant:small-caps;padding:0 1rem;font-size:.9rem}.gg-medium,.gg-medium-withtext{min-width:calc(var(--app-standard-height) / 1.2);min-height:calc(var(--app-standard-height) / 1.2);max-height:calc(var(--app-standard-height) / 1.2);flex-direction:row}.gg-medium img{width:calc(var(--app-standard-height) / 2.4);margin:0}.gg-medium-withtext img{width:calc(var(--app-standard-height) / 2.4);margin-left:.5rem}.gg-medium-withtext span{padding:0 1rem 0 .5rem;font-size:.9rem}.gg-small,.gg-small-withtext{min-width:calc(var(--app-standard-height) / 2);min-height:calc(var(--app-standard-height) / 2);max-height:calc(var(--app-standard-height) / 2);flex-direction:row}.gg-small img{width:calc(var(--app-standard-height) / 3);margin:0}.gg-small-withtext img{width:calc(var(--app-standard-height) / 3);margin-left:.5rem}.gg-small-withtext span{padding:0 .5rem 0 .3rem;font-size:.9rem}.gg-button:hover:not(:disabled),.gg-select:hover:not(:disabled),.gg-input:hover:not(:disabled),.gg-textarea:hover:not(:disabled),.gg-icon-button:hover:not(:disabled){background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{opacity:1;background-color:#0000}.gg-tabs{cursor:pointer;grid-auto-flow:column;padding-bottom:1rem;font-size:1rem;display:grid}.gg-tab{border:none;border-bottom:var(--app-standard-border);cursor:pointer;color:var(--text-color);background:0 0;padding:.5rem}.gg-tab.active{border-bottom:solid 1px var(--text-color)}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{color:var(--text-color);background-color:#0000;border:none;flex-direction:column;display:flex}.girafe-button-big:hover,.girafe-button-large:hover,.girafe-button-small:hover,.girafe-button-tiny:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.girafe-button-big.dark,.girafe-button-large.dark,.girafe-button-small.dark,.girafe-button-tiny.dark{background-color:var(--bkg-color);filter:invert()}.girafe-button-big{width:var(--app-standard-height);height:var(--app-standard-height);align-items:center;padding:1rem}.girafe-button-big img{overflow:hidden}.girafe-button-large{flex-direction:row}.girafe-button-large img{height:2rem;margin:.3rem}.girafe-button-large span{height:2rem;margin:.3rem;line-height:2rem}.girafe-button-small{min-width:calc(var(--app-standard-height) / 2);height:calc(var(--app-standard-height) / 2);align-items:center;padding:.5rem}.girafe-button-small img{overflow:hidden}.girafe-button-small span{text-align:left;text-overflow:ellipsis;width:100%;overflow:hidden}.girafe-button-tiny{align-items:center;width:1rem;height:1rem;padding:0}.girafe-button-tiny img{overflow:hidden}.girafe-onboarding-theme{background-color:var(--bkg-color)!important;color:var(--text-color)!important}.girafe-onboarding-theme button{background-color:var(--bkg-color)!important;color:var(--text-color)!important;text-shadow:none!important}.girafe-onboarding-theme button.driver-popover-close-btn{z-index:10000}.tippy-box{background-color:var(--bkg-color)!important;border:var(--app-standard-border)!important}.tippy-content{color:var(--text-color)!important}.tippy-arrow{color:var(--bkg-color)!important}.tippy-box[data-theme~=error]{background-color:var(--error-color);white-space:pre-line}div.tippy-box[data-theme=image-popup]{border:var(--app-standard-border)!important;& div.tippy-content{background-color:var(--bkg-color)!important;& img{max-width:20rem;max-height:20rem}}& div.tippy-arrow{color:var(--bkg-color)!important}}
</style>
<style>${this.customStyle}</style>
<div id="panel"><div id="content"><div class="btn-group-flex"><button id="draw-profile-btn" class="${this.crossSectionState.drawProfile ? 'gg-button active' : 'gg-button'}" tip="draw_profile_help" onclick="${() => this.toggleLineDraw()}" i18n="draw_profile">Draw</button> <button id="delete-profile-btn" class="gg-button" tip="delete_help" onclick="${() => this.deleteProfile()}" i18n="delete">Delete</button></div><div class="btn-group-flex"><label for="section-width-btn" i18n="profile_width" class="gg-label">Width [m]</label> <input id="section-width-btn" class="gg-input" type="number" value="${this.crossSectionState.sectionWidthSettings.value}" min="${this.crossSectionState.sectionWidthSettings.min}" max="${this.crossSectionState.sectionWidthSettings.max}" step="${this.crossSectionState.sectionWidthSettings.step}" oninput="${(e) => this.setSectionWidth(parseFloat(e.target.value))}"></div><div class="btn-group-flex"><button id="reset-zoom-btn" class="gg-button" tip="profile_reset_view_help" onclick="${() => this.resetZoom()}" i18n="profile_reset_view">Reset view</button> <button id="sync-views-btn" class="${this.crossSectionState.syncViews ? 'gg-button active' : 'gg-button'}" tip="profile_sync_view_help" onclick="${() => this.setViewSync(!this.crossSectionState.syncViews)}" i18n="profile_sync_view">Sync. views</button></div><div class="btn-group-flex"><button class="gg-icon-button gg-big" tip="profile_shift_up_help" onclick="${() => this.shiftLinestring([0.0, this.crossSectionState.linestringShift])}"><img src="icons/arrow_up.svg" alt="${this.context.i18nManager.getTranslation('profile_shift_up_help')}"></button> <button class="gg-icon-button gg-big" tip="profile_shift_down_help" onclick="${() => this.shiftLinestring([0.0, -this.crossSectionState.linestringShift])}"><img src="icons/arrow_down.svg" alt="${this.context.i18nManager.getTranslation('profile_shift_down_help')}"></button> <button class="gg-icon-button gg-big" tip="profile_shift_left_help" onclick="${() => this.shiftLinestring([-this.crossSectionState.linestringShift, 0.0])}"><img src="icons/arrow_left.svg" alt="${this.context.i18nManager.getTranslation('profile_shift_left_help')}"></button> <button class="gg-icon-button gg-big" tip="profile_shift_right_help" onclick="${() => this.shiftLinestring([this.crossSectionState.linestringShift, 0.0])}"><img src="icons/arrow_right.svg" alt="${this.context.i18nManager.getTranslation('profile_shift_right_help')}"></button></div><div class="btn-group-flex"><div class="cell"><label for="z-ratio-btn" class="gg-label">${this.context.i18nManager.getTranslation('profile_exaggeration')} (${this.crossSectionState.verticalExaggerationSettings.value})</label><div style="display: flex; align-items: center"><input id="z-ratio-btn" type="range" class="gg-range" min="${this.crossSectionState.verticalExaggerationSettings.min}" max="${this.crossSectionState.verticalExaggerationSettings.max}" step="${this.crossSectionState.verticalExaggerationSettings.step}" value="${this.crossSectionState.verticalExaggerationSettings.value}" oninput="${(e) => this.setVerticalExaggeration(parseFloat(e.target.value))}" style="flex: 1; min-width: 0; box-sizing: border-box"> <button id="z-ratio-reset-btn" class="reset-btn" tip="profile_exaggeration_reset_help" onclick="${() => this.setVerticalExaggeration(this.crossSectionState.verticalExaggerationSettings.default)}"><img src="icons/restart_alt.svg" alt="${this.context.i18nManager.getTranslation('profile_exaggeration_reset_help')}"></button></div></div></div><div class="btn-group-flex"><div class="cell"><label for="point-size-label" class="gg-label">${this.context.i18nManager.getTranslation('profile_point_size')} (${this.crossSectionState.pointSizeSettings.value})</label><div style="display: flex; align-items: center"><input id="point-size-btn" type="range" class="gg-range" min="${this.crossSectionState.pointSizeSettings.min}" max="${this.crossSectionState.pointSizeSettings.max}" step="${this.crossSectionState.pointSizeSettings.step}" value="${this.crossSectionState.pointSizeSettings.value}" oninput="${(e) => this.setPointSize(parseFloat(e.target.value))}" style="flex: 1; min-width: 0; box-sizing: border-box"> <button id="point-size-reset-btn" class="reset-btn" tip="profile_point_size_reset_help" onclick="${() => this.setPointSize(this.crossSectionState.pointSizeSettings.default)}"><img src="icons/restart_alt.svg" alt="${this.context.i18nManager.getTranslation('profile_point_size_reset_help')}"></button></div></div></div><div class="btn-group-flex"><label for="background-color-btn" i18n="profile_background_color" class="gg-label">Background color</label> <input id="background-color-btn" class="gg-input" type="color" value="${this.crossSectionState.backgroundColor}" oninput="${(e) => this.setBackgroundColor(e.target.value)}"></div><div class="btn-group-flex"><label for="sequential-color-btn" i18n="profile_colormap" class="gg-label">Colorscale</label> <select id="sequential-color-btn" class="gg-select" oninput="${(e) => this.setColorPalette(e.target.value)}"><option value="spectral" ?selected="${this.crossSectionState.colorPalette === 'spectral'}" i18n="palette_option_spectral">Spectral<option value="greys" ?selected="${this.crossSectionState.colorPalette === 'greys'}" i18n="palette_option_greys">Greys<option value="blues" ?selected="${this.crossSectionState.colorPalette === 'blues'}" i18n="palette_option_blues">Blues<option value="viridis" ?selected="${this.crossSectionState.colorPalette === 'viridis'}" i18n="palette_option_viridis">Viridis<option value="magma" ?selected="${this.crossSectionState.colorPalette === 'magma'}" i18n="palette_option_magma">Magma</select></div><div class="option"><label for="grid-btn" i18n="profile_toggle_grid" class="gg-label">Show grid</label> <input id="grid-btn" class="gg-checkbox" ?checked="${this.crossSectionState.gridVisible}" type="checkbox" onchange="${(e) => this.setGridVisibility(e.target.checked)}"></div><h3 i18n="profile_pointcloud">Pointclouds</h3><div class="btn-group-flex loader-progress"><div class="progress-wrapper" tip="profile_load_indicator_help"><progress id="load-progress" class="gg-progress" value="${this.crossSectionState.numberOfPoints}" max="${this.crossSectionState.maxNumberOfPoints}"></progress> <span class="progress-label">${(this.crossSectionState.loading) ? uHtml `<img src="icons/progress.svg" alt="Loading" class="gg-spin gg-small progress-icon">` : uHtml ``} ${this.crossSectionState.numberOfPoints} / ${this.crossSectionState.maxNumberOfPoints}</span></div></div><div>${this.crossSectionState.datasets.map(f => uHtml `<div class="dataset-row"><input type="checkbox" id="${f.id}" class="gg-checkbox" ?checked="${f.active}" onchange="${() => this.toggleVisibility(f.id)}"> <span class="dataset-name" i18n="${f.id}">${f.id}</span> <select class="gg-select" oninput="${(e) => this.setColorVariable(f.id, e.target.value)}"><option value="uniform" ?selected="${f.colorby === 'uniform'}" i18n="color_option_uniform">Uniform<option value="natural" ?selected="${f.colorby === 'natural'}" i18n="color_option_natural">Natural<option value="intensity" ?selected="${f.colorby === 'intensity'}" i18n="color_option_intensity">Intensity<option value="classification" ?selected="${f.colorby === 'classification'}" i18n="color_option_classification">Classification</select> <input id="uniform-color-btn" type="color" value="${f.color}" oninput="${(e) => this.setColor(f.id, e.target.value)}"></div>`)}</div><h3 i18n="profile_measure_and_annotate">Measurements and annotations</h3><div class="btn-group-flex"><button id="draw-measurements-btn" class="${this.crossSectionState.drawMeasurement ? 'gg-button active' : 'gg-button'}" tip="profile_measurement_help" onclick="${() => this.toggleMeasureDraw()}" i18n="profile_measurement" ?disabled="${!this.crossSectionState.enableMeasurement}">Measure</button> <button id="delete-measurements-btn" class="gg-button" tip="profile_delete_measurements_help" onclick="${() => this.deleteAllMeasurements()}" i18n="profile_delete_measurements">Delete all</button></div><div class="scrollable-table-container"><table id="measurements-table" class="scrollable-table"><thead><tr><th class="table-cell sticky-header" style="text-align: center"><th class="table-cell sticky-header" style="text-align: right" i18n="profile_table_dist">DIST.<th class="table-cell sticky-header" style="text-align: right" i18n="profile_table_slope">SLOPE.<th class="table-cell sticky-header" style="text-align: center"><tbody></table></div><div class="btn-group-flex"><button id="draw-markers-btn" class="${this.crossSectionState.drawMarker ? 'gg-button active' : 'gg-button'}" tip="profile_draw_markers_help" onclick="${() => this.toggleMarkerDraw()}" i18n="profile_draw_markers" ?disabled="${!this.crossSectionState.enableAnnotation}">Annotate</button> <button id="delete-markers-btn" class="gg-button" tip="profile_delete_markers_help" onclick="${() => this.deleteAllMarkers()}" i18n="profile_delete_markers">Delete all</button></div><div class="scrollable-table-container"><table id="markers-table" class="scrollable-table"><thead><tr><th class="sticky-header" style="text-align: center" i18n="profile_table_id">ID<th class="sticky-header" style="text-align: right" i18n="profile_table_coord">COORD.<th class="sticky-header" style="text-align: center"><th class="sticky-header" style="text-align: center"><th class="sticky-header" style="text-align: center"><tbody></table></div><h3 i18n="profile_print_title">Print</h3><div class="btn-group-flex"><select id="print-profile-format-btn" class="gg-select" oninput="${(e) => this.setPrintFileFormat(e.target.value)}"><option value="svg" i18n="SVG">SVG</select> <button id="print-profile-btn" class="gg-button" tip="profile_print_help" onclick="${() => this.printPlot(this.crossSectionState.printFileFormat)}" i18n="profile_print">Print</button></div><h3 i18n="profile_download_title">Downloads</h3><div class="text-label" i18n="profile_markers_download">Markers</div><div class="btn-group-flex"><select id="download-markers-format-btn" class="gg-select" oninput="${(e) => this.setAnnotationsFileFormat(e.target.value)}"><option value="kml" i18n="KML">KML<option value="geojson" i18n="GeoJSON">GeoJSON<option value="gpx" i18n="GPX">GPX</select> <button id="download-markers-btn" class="gg-button" tip="download_help" onclick="${() => this.exportFeature(this.points, 'markers', this.crossSectionState.downloadAnnotationsFormat)}" i18n="download" ?disabled="${!this.crossSectionState.enableAnnotationsDownload}">Download</button></div><div class="text-label" i18n="profile_linestring_download">Profile line</div><div class="btn-group-flex"><select id="download-linestring-format-btn" class="gg-select" oninput="${(e) => this.setLineFileFormat(e.target.value)}"><option value="kml" i18n="KML">KML<option value="geojson" i18n="GeoJSON">GeoJSON<option value="gpx" i18n="GPX">GPX</select> <button id="download-linestring-btn" class="gg-button" tip="download_help" onclick="${() => this.exportFeature([this.linestring], 'linestring', this.crossSectionState.downloadLinestringFormat)}" i18n="download" ?disabled="${!this.crossSectionState.enableLinestringDownload}">Download</button></div></div></div>
${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`;
};
crossSectionState;
eventsCallbacks = [];
darkFrontendMode = false;
isPanelVisible = false;
panelTitle = 'cross-section-settings';
panelTogglePath = 'interface.crossSectionPanelVisible';
get map() {
return this.context.mapManager.getMap();
}
linestring;
linestringSource;
linesLayer;
domainLinestring;
domainLinestringSource;
domainLineStringLayer;
polygon;
polygonSource;
polygonLayer;
pointer;
pointerSource;
pointerLayer;
points;
pointsSource;
pointsLayer;
drawInteraction;
modifyInteraction;
linestringLength = 0.0;
markersTable = null; // reference to 'markers-table' shadow DOM element
measurementsTable = null; // reference to 'measurements-table' shadow DOM element
// @ts-expect-error: initiator issue
parser = new OL3Parser(undefined, undefined);
iconStyle = new Style({
image: new Icon({
color: '#FF8C00',
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
src: 'icons/adjust.svg'
})
});
pointStyleFunction = (feature) => {
return new Style({
image: new Circle({
radius: 7,
fill: new Fill({ color: feature.get('show') ? [255, 255, 0, 0.75] : [0, 0, 0, 0.75] }),
stroke: new Stroke({ color: feature.get('show') ? '#FF0000' : '#000000', width: 2 })
}),
text: new Text({
text: `${feature.get('label')}`,
font: '16px sans-serif',
textAlign: 'center',
justify: 'center',
textBaseline: 'middle',
placement: 'point',
fill: new Fill({ color: [255, 255, 255, 1] }),
offsetY: -30,
backgroundFill: new Fill({ color: [0, 0, 0, 1] }),
padding: [5, 7, 5, 7]
})
});
};
constructor() {
super('cross-section-settings');
}
initializeMapElements() {
this.initializeLinestring();
this.initializeDomainLinestring();
this.initializePolygon();
this.initializePointer();
this.initializePointsLayer();
this.initializeInteractions();
}
initializeLinestring() {
this.linestring = new Feature({
id: 'cross-section-linestring',
geometry: new LineString([])
});
this.linestringSource = new VectorSource();
this.linestringSource.on('addfeature', (e) => {
this.handleAddFeature(e);
});
this.linesLayer = new VectorLayer({
source: this.linestringSource,
style: {
'fill-color': 'rgba(255, 255, 255, 0.2)',
'stroke-color': '#ff0000',
'stroke-width': 2
},
properties: {
addToPrintedLayers: true,
altitudeMode: 'clampToGround'
}
});
this.map.addLayer(this.linesLayer);
}
initializeDomainLinestring() {
this.domainLinestring = new Feature({
id: 'domainLinestring',
geometry: new LineString([])
});
this.domainLinestringSource = new VectorSource({ features: [] });
this.domainLineStringLayer = new VectorLayer({
source: this.domainLinestringSource,
style: {
'stroke-color': '#0000ff',
'stroke-width': 2
},
properties: {
addToPrintedLayers: true,
altitudeMode: 'clampToGround'
}
});
this.map.addLayer(this.domainLineStringLayer);
}
initializePolygon() {
this.polygon = new Feature({
id: 'linestringBuffer',
geometry: new Polygon([])
});
this.polygonSource = new VectorSource({ features: [] });
this.polygonLayer = new VectorLayer({
source: this.polygonSource,
style: {
'fill-color': 'rgba(255, 255, 255, 0.2)',
'stroke-color': '#ff0000',
'stroke-width': 2
},
properties: {
addToPrintedLayers: true,
altitudeMode: 'clampToGround'
}
});
this.map.addLayer(this.polygonLayer);
}
initializePointer() {
this.pointer = new Feature({
geometry: new Point([]),
style: this.iconStyle
});
this.pointerSource = new VectorSource({
features: [],
wrapX: false
});
this.pointerLayer = new VectorLayer({
source: this.pointerSource,
style: this.iconStyle,
properties: {
addToPrintedLayers: true,
altitudeMode: 'clampToGround'
}
});
this.map.addLayer(this.pointerLayer);
}
initializePointsLayer() {
this.points = [];
this.pointsSource = new VectorSource({
features: this.points,
wrapX: false
});
this.pointsLayer = new VectorLayer({
source: this.pointsSource,
style: this.pointStyleFunction,
properties: {
addToPrintedLayers: true,
altitudeMode: 'clampToGround'
}
});
this.map.addLayer(this.pointsLayer);
}
initializeInteractions() {
this.initializeDrawInteraction();
this.initializeModifyInteraction();
}
handleAddFeature(e) {
const geometry = e.feature?.getGeometry();
this.linestring.setGeometry(geometry);
this.crossSectionState.linestringCoordinates = geometry.getCoordinates();
}
initializeDrawInteraction() {
this.drawInteraction = new Draw({
source: this.linestringSource,
type: 'LineString',
freehand: false,
// noModifierKeys(e) is the default condition for drawing
// canExecute: If another tool is exclusively drawing, this interaction will be prevented from reacting
condition: (e) => noModifierKeys(e) && this.canExecute('map.draw')
});
this.drawInteraction.on('drawstart', (_e) => {
this.deleteProfile();
});
// Listen to drawing end event (note: the DRAWEND event is dispatched before inserting the feature in the source)
this.drawInteraction.on('drawend', (e) => {
this.handleAddFeature(e);
});
}
initializeModifyInteraction() {
this.modifyInteraction = new Modify({
source: this.linestringSource,
condition: (e) => primaryAction(e) && this.canExecute('map.modify')
});
this.modifyInteraction.on('modifystart', (_e) => {
this.polygonSource.clear();
this.domainLinestringSource.clear();
this.pointerSource.clear();
});
this.modifyInteraction.on('modifyend', (_e) => {
// The linestring coordinates are only updated when the modify interaction has ended, to
// avoid redrawing the buffer and domain linestring during modification
this.crossSectionState.linestringCoordinates = this.linestring.getGeometry().getCoordinates();
});
}
updateMarkers(polygon) {
if (!this.linestring) {
console.warn('updateMarkers: The cross-section linestring is undefined, unable to update markers');
return;
}
const linestringGeom = this.linestring.getGeometry();
this.points.forEach((el) => {
const coord = el.getGeometry()?.getCoordinates();
if (!coord) {
console.warn('updateMarkers: Map point feature coordinate is undefined, unable to update markers');
return;
}
// Check if the marker is inside the polygon (buffer around the linestring)
const inside = polygon.getGeometry()?.intersectsCoordinate(coord);
const target = this.crossSectionState.markers.find((x) => x.id == el.get('id'));
if (target) {
target.show = inside;
el.set('show', inside);
if (inside) {
// Get map coordinates of the closest point on the profile linestring
const closestPoint = linestringGeom.getClosestPoint(coord);
// Get linear coordinates of the closest point on the profile linestring and update marker scatterplot position in state manager
target.x = this.getDistanceAtCoord(linestringGeom, closestPoint);
}
}
});
}
drawLinestringBuffer() {
if (this.crossSectionState.linestringCoordinates.length < 2) {
return;
}
if (!this.linestring) {
console.warn('updateLinestringBuffer: Linestring is undefined, unable to update buffer');
return;
}
this.polygonSource.clear();
const geometry = this.linestring.getGeometry();
const jstsGeom = this.parser.read(geometry);
const bufferParams = new BufferParameters(BufferParameters.DEFAULT_QUADRANT_SEGMENTS, BufferParameters.CAP_FLAT, BufferParameters.JOIN_MITRE, BufferParameters.DEFAULT_MITRE_LIMIT);
const bo = new BufferOp(jstsGeom, bufferParams);
const buffered = bo.getResultGeometry(this.crossSectionState.sectionWidthSettings.value / 2);
const mypoly = this.parser.write(buffered);
this.polygon.setGeometry(mypoly);
this.polygonSource.addFeature(this.polygon);
this.updateMarkers(this.polygon);
}
updateLinestringCoordinates() {
this.pointerSource.clear();
this.domainLinestringSource.clear();
this.polygonSource.clear();
if (this.crossSectionState.linestringCoordinates.length >= 2) {
this.linestring.getGeometry().setCoordinates(this.crossSectionState.linestringCoordinates);
this.linestringLength = getDistance(this.linestring.getGeometry().getCoordinates(), this.context.stateManager.state.projection);
this.drawDomainLinestring();
this.drawLinestringBuffer();
}
else {
this.linestringSource.clear();
}
}
drawDomainLinestring() {
if (this.crossSectionState.linestringCoordinates.length < 2) {
return;
}
const geometry = this.linestring.getGeometry();
if (!geometry) {
console.warn('drawDomainLinestring: Linestring geometry is undefined, unable to clip');
return;
}
if (geometry.getCoordinates().length < 2) {
return;
}
const linestringLength = getDistance(geometry.getCoordinates(), this.context.stateManager.state.projection);
// Get map coordinates of profile domain extent
const fStart = Math.max(0.0, this.crossSectionState.domain.xmin / linestringLength);
const fEnd = Math.min(1.0, this.crossSectionState.domain.xmax / linestringLength);
if (fStart >= 0.0 && fStart <= 1.0 && fEnd >= 0.0 && fEnd <= 1.0) {
const coordStart = geometry.getCoordinateAt(fStart);
const coordEnd = geometry.getCoordinateAt(fEnd);
const lineStringCoords = geometry.getCoordinates();
const coords = [];
coords.push(coordStart);
for (const coord of lineStringCoords) {
const distance = this.getDistanceAtCoord(geometry, coord);
if (distance >= this.crossSectionState.domain.xmin && distance <= this.crossSectionState.domain.xmax) {
coords.push(coord);
}
}
coords.push(coordEnd);
this.domainLinestring.getGeometry().setCoordinates(coords);
if (this.domainLinestringSource.getFeatures().length === 0) {
this.domainLinestringSource.addFeature(this.domainLinestring);
}
// Zoom to extent
if (this.crossSectionState.syncViews) {
const view = this.map.getView();
view.setCenter(this.domainLinestring.getGeometry().getCoordinateAt(0.5));
}
}
}
// Get distance from start on linestring at given coordinate
getDistanceAtCoord(lineStringGeom, coord) {
const lineStringCoords = lineStringGeom.getCoordinates();
let distance = 0;
// Iterate over each segment of the linestring
for (let i = 0; i < lineStringCoords.length - 1; i++) {
const p1 = lineStringCoords[i];
const p2 = lineStringCoords[i + 1];
const segment = new LineString([p1, p2]);
const intersects = segment.intersectsCoordinate(coord);
if (intersects) {
distance += getDistance([p1, coord], this.context.stateManager.state.projection);
break;
}
distance += getDistance([p1, p2], this.context.stateManager.state.projection);
}
return distance;
}
shiftLinestring(shift = [0.0, 0.0]) {
this.crossSectionState.linestringCoordinates = this.crossSectionState.linestringCoordinates.map((x) => [x[0] + shift[0], x[1] + shift[1]]);
}
drawPointer(coords) {
const geometry = this.pointer.getGeometry();
if (!geometry) {
return;
}
geometry.setCoordinates(coords);
if (this.pointerSource.getFeatures().length === 0) {
this.pointerSource.addFeature(this.pointer);
}
}
drawMapMarkers() {
if (!this.linestring) {
console.warn('drawMapMarkers: Linestring is undefined, unable to draw markers on map');
return;
}
// Clear markers on the map
this.points = [];
this.crossSectionState.markers.forEach((el) => {
// Update markers in state manager
if (el.update) {
const coords = this.linestring.getGeometry().getCoordinateAt(el.x / this.linestringLength);
el.xm = coords[0];
el.ym = coords[1];
}
el.update = false;
// Update markers on map
const mapPoint = new Feature({
geometry: new Point([el.xm, el.ym]),
id: el.id,
label: el.label,
Z: el.y.toFixed(2),
size: 20,
show: el.show
});
mapPoint.setId(el.id);
this.points.push(mapPoint);
});
// Refresh points layer on map
this.pointsSource.clear();
this.pointsSource.addFeatures(this.points);
this.pointsLayer.setSource(this.pointsSource);
this.pointsLayer.changed();
}
addInteractions() {
const arr = this.map.getInteractions().getArray();
if (!arr.includes(this.drawInteraction)) {
this.map.addInteraction(this.drawInteraction);
}
if (!arr.includes(this.modifyInteraction)) {
this.map.addInteraction(this.modifyInteraction);
}
}
removeInteractions() {
this.map.removeInteraction(this.drawInteraction);
this.map.removeInteraction(this.modifyInteraction);
}
toggleMeasureDraw() {
this.crossSectionState.drawMeasurement = !this.crossSectionState.drawMeasurement;
}
toggleMarkerDraw() {
this.crossSectionState.drawMarker = !this.crossSectionState.drawMarker;
}
toggleLineDraw() {
this.crossSectionState.drawProfile = !this.crossSectionState.drawProfile;
}
toggleVisibility(id) {
const ds = this.crossSectionState.datasets.find((d) => d.id === id);
if (ds) {
ds.active = !ds.active;
}
}
setColor(id, color) {
const ds = this.crossSectionState.datasets.find((d) => d.id === id);
if (ds) {
ds.color = color;
ds.colorby = 'uniform';
}
}
setColorVariable(id, colorby) {
const ds = this.crossSectionState.datasets.find((d) => d.id === id);
if (ds) {
ds.colorby = colorby;
}
}
setLineDrawingMode(val) {
this.crossSectionState.drawProfile = val;
if (val) {
this.addInteractions();
}
else {
this.removeInteractions();
}
super.render();
}
setSectionWidth(val) {
if (val <= 0 ||
val < this.crossSectionState.sectionWidthSettings.min ||
val > this.crossSectionState.sectionWidthSettings.max) {
val = this.crossSectionState.sectionWidthSettings.default;
console.warn(`setSectionWidth: Width is not within accepted range [${this.crossSectionState.sectionWidthSettings.min}, ${this.crossSectionState.sectionWidthSettings.max}]. Resetting to default value`);
}
this.crossSectionState.sectionWidthSettings.value = val;
}
setVerticalExaggeration(val) {
if (val <= 0 ||
val < this.crossSectionState.verticalExaggerationSettings.min ||
val > this.crossSectionState.verticalExaggerationSettings.max) {
val = this.crossSectionState.verticalExaggerationSettings.default;
console.warn(`setVerticalExaggeration: vertical exaggeration is not within accepted range [${this.crossSectionState.verticalExaggerationSettings.min}, ${this.crossSectionState.verticalExaggerationSettings.max}]. Resetting to default value`);
}
this.crossSectionState.verticalExaggerationSettings.value = val;
super.render();
}
setPointSize(val) {
if (val <= 0 ||
val < this.crossSectionState.pointSizeSettings.min ||
val > this.crossSectionState.pointSizeSettings.max) {
val = this.crossSectionState.pointSizeSettings.default;
console.warn(`setPointSize: point size is not within accepted range [${this.crossSectionState.pointSizeSettings.min}, ${this.crossSectionState.pointSizeSettings.max}]. Resetting to default value`);
}
this.crossSectionState.pointSizeSettings.value = val;
super.render();
}
setGridVisibility(val) {
this.crossSectionState.gridVisible = val;
}
setBackgroundColor(val) {
this.crossSectionState.backgroundColor = val;
}
setColorPalette(val) {
this.crossSectionState.colorPalette = val;
}
exportFeature(features, filename, format) {
switch (format) {
case 'geojson': {
const geoJsonString = new GeoJSON().writeFeatures(features, {
featureProjection: this.state.projection
});
download(geoJsonString, filename + '.geojson', 'application/geo+json');
break;
}
case 'kml': {
const kmlString = new KML().writeFeatures(features, {
featureProjection: this.state.projection
});
download(kmlString, filename + '.kml', 'application/vnd.google-earth.kml+xml');
break;
}
case 'gpx': {
const gpxString = new GPX().writeFeatures(features, {
featureProjection: this.state.projection
});
download(gpxString, filename + '.gpx', 'application/gpx+xml');
break;
}
}
}
renderMeasurementsTable(table, records) {
table.tBodies[0].remove();
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
// Add rows
records.forEach((_d) => {
const from = this.crossSectionState.markers.find((x) => x.id === _d['from']);
const to = this.crossSectionState.markers.find((x) => x.id === _d['to']);
const newRow = tableBody.insertRow(-1);
newRow.id = `row-${_d.id}`;
// Add cell to the row
// FROM > TO
const cell1 = newRow.insertCell(-1);
cell1.classList.add('table-cell');
cell1.style.setProperty('text-align', 'center');
cell1.innerHTML = `${from.label} → ${to.label}`;
// DISTANCE
let cell = newRow.insertCell(-1);
cell.classList.add('table-cell');
cell.style.setProperty('text-align', 'right');
cell.innerHTML = `${_d['distance'].toFixed(2)}`;
// SLOPE
cell = newRow.insertCell(-1);
cell.classList.add('table-cell');
cell.style.setProperty('text-align', 'right');
cell.innerHTML = `${(100 * _d['slope']).toFixed(2)}%`;
// COPY BUTTON
const btn1 = document.createElement('img');
btn1.title = 'Copy to clipboard';
btn1.width = 20;
btn1.classList.add('action-btn');
btn1.src = 'icons/content_copy.svg';
btn1.onclick = (_e) => {
const str = `${_d['id']}, ${_d['from']}, ${_d['to']}, ${_d['distance']}, ${_d['slope']}`;
navigator.clipboard.writeText(str);
};
const cell4 = newRow.insertCell(-1);
cell4.classList.add('table-cell');
cell4.style.setProperty('text-align', 'center');
cell4.appendChild(btn1);
});
}
renderAnnotationsTable(table, records) {
table.tBodies[0].remove();
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
// Add rows
records.forEach((_d) => {
const newRow = tableBody.insertRow(-1);
newRow.id = `row-${_d.id}`;
// Add cells to the row
// MARKER ID
const cell1 = newRow.insertCell(-1);
cell1.classList.add('table-cell');
cell1.style.setProperty('text-align', 'center');
cell1.innerHTML = `${_d['label']}`;
// MARKER X
const cell2 = newRow.insertCell(-1);
cell2.classList.add('table-cell');
cell2.style.setProperty('text-align', 'right');
cell2.innerHTML = `${_d['xm'].toFixed(2)}<br>${_d['ym'].toFixed(2)}<br>${_d['y'].toFixed(2)}`;
// COPY BUTTON
const btn1 = document.createElement('img');
btn1.title = 'Copy to clipboard';
btn1.width = 20;
btn1.classList.add('action-btn');
btn1.src = 'icons/content_copy.svg';
btn1.onclick = (_e) => {
const str = `${_d['id']}, ${_d['xm']}, ${_d['ym']}, ${_d['y']}, ${_d['x']}`;
navigator.clipboard.writeText(str);
};
const cell4 = newRow.insertCell(-1);
cell4.classList.add('table-cell');
cell4.style.setProperty('text-align', 'center');
cell4.appendChild(btn1);
// FOCUS BUTTON
const btn2 = document.createElement('img');
btn2.title = 'Zoom to marker on map';
btn2.width = 20;
btn2.classList.add('action-btn');
btn2.src = 'icons/loupe.svg';
btn2.onclick = (_e) => {
this.zoomToMarker(`${_d['id']}`);
};
const cell5 = newRow.insertCell(-1);
cell5.classList.add('table-cell');
cell5.style.setProperty('text-align', 'center');
cell5.appendChild(btn2);
// DELETE BUTTON
const btn3 = document.createElement('img');
btn3.title = 'Delete marker';
btn3.width = 20;
btn3.classList.add('action-btn');
btn3.src = 'icons/delete_forever.svg';
btn3.onclick = (_e) => {
this.deleteMarker(_d['id']);
};
const cell6 = newRow.insertCell(-1);
cell6.classList.add('table-cell');
cell6.style.setProperty('text-align', 'center');
cell6.appendChild(btn3);
});
}
deleteProfile() {
this.crossSectionState.linestringCoordinates = [];
this.crossSectionState.numberOfPoints = 0;
}
deleteMarker(id) {
const index = this.crossSectionState.markers.findIndex((el) => el.id === id);
if (index !== -1) {
this.crossSectionState.markers.splice(index, 1);
}
}
deleteAllMarkers() {
for (let i = this.crossSectionState.markers.length - 1; i >= 0; i--) {
if (this.crossSectionState.markers[i].feature === 'marker') {
this.crossSectionState.markers.splice(i, 1);
}
}
/* Note: the scatterplot class can also use the custom event below to delete markers (instead of reacting to changes
in the markers array in the state manager) Dispatch a custom event when the delete annotations button is clicked
*/
/*
const event: CustomEvent = new CustomEvent('delete-markers', {
bubbles: true, // Allows the event to bubble up to the parent
composed: true // Allows the event to pass through the shadow DOM
});
this.dispatchEvent(event);
*/
}
deleteAllMeasurements() {
const event = new CustomEvent('delete-measurements', {
bubbles: true,
composed: true
});
this.dispatchEvent(event);
}
resetZoom() {
this.crossSectionState.zoomUpdate = true;
this.crossSectionState.zoom = { k: 1.0, tx: 0.0, ty: 0.0 };
}
zoomToMarker(id) {
const view = this.map.getView();
const target = this.pointsSource.getFeatureById(id);
if (target)
view.fit(target.getGeometry(), {
maxZoom: 17,
size: [200, 200]
});
}
setViewSync(val) {
this.crossSectionState.syncViews = val;
}
printPlot(printFileFormat) {
const event = new CustomEvent('print-canvas', {
detail: { format: printFileFormat },
bubbles: true,
composed: true
});
this.dispatchEvent(event);
}
setPrintFileFormat(val) {
this.crossSectionState.printFileFormat = val;
}
setAnnotationsFileFormat(val) {
this.crossSectionState.downloadAnnotationsFormat = val;
}
setLineFileFormat(val) {
this.crossSectionState.downloadLinestringFormat = val;
}
handleCursorDomainCoordinatesChange(cursorDomainCoordinates) {
if (this.crossSectionState.linestringCoordinates.length < 2) {
console.warn('handleCursorDomainCoordinatesChange: Linestring coordinates are undefined, unable to update pointer coordinates');
return;
}
if (!this.linestring) {
console.warn('handleCursorDomainCoordinatesChange: Linestring is undefined, unable to update pointer coordinates');
return;
}
const geometry = this.linestring.getGeometry();
if (!geometry) {
console.warn('handleCursorDomainCoordinatesChange: Linestring geometry is undefined, unable to update pointer coordinates');
return;
}
const f = cursorDomainCoordinates[0] / this.linestringLength;
if (f >= 0.0 && f <= 1.0) {
const coords = geometry.getCoordinateAt(f);
this.drawPointer(coords);
}
else {
// If the pointer is not located within the extent of the linestring, then clear the pointer from the map
this.pointerSource.clear();
}
}
// Renders the component or the empty component depending on visibility attribute
render() {
if (this.isPanelVisible) {
this.renderComponent();
}
else {
this.renderEmptyComponent();
}
}
renderComponent() {
super.render();
super.girafeTranslate();
// Tables
this.markersTable = this.shadowRoot.getElementById('markers-table');
this.measurementsTable = this.shadowRoot.getElementById('measurements-table');
// Enable line drawing mode
this.setLineDrawingMode(true);
// Tooltips
this.registerEvents();
}
// Hide the panel and removes listeners
renderEmptyComponent() {
this.deleteProfile();
this.removeInteractions();
this.unregisterEvents();
this.renderEmpty();
}
registerEvents() {
// Register listeners in state
this.registerInteractionListener('map.select', true);
this.registerInteractionListener('map