qwc2
Version:
QGIS Web Client
784 lines (778 loc) • 35.2 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
* Copyright 2017-2024 Sourcepole AG
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Line } from "react-chartjs-2";
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import axios from 'axios';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Filler, BubbleController } from 'chart.js';
import FileSaver from 'file-saver';
import isEmpty from 'lodash.isempty';
import PropTypes from 'prop-types';
import { v4 as uuidv4 } from 'uuid';
import { addMarker, removeMarker } from '../actions/layers';
import { changeMeasurementState } from '../actions/measurement';
import Icon from '../components/Icon';
import ResizeableWindow from '../components/ResizeableWindow';
import Spinner from '../components/widgets/Spinner';
import CoordinatesUtils from '../utils/CoordinatesUtils';
import { getElevationInterface } from '../utils/ElevationInterface';
import LayerUtils from '../utils/LayerUtils';
import LocaleUtils from '../utils/LocaleUtils';
import MapUtils from '../utils/MapUtils';
import MeasureUtils from '../utils/MeasureUtils';
import MiscUtils from '../utils/MiscUtils';
import VectorLayerUtils from '../utils/VectorLayerUtils';
import './style/HeightProfile.css';
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Filler, BubbleController);
var HeightProfilePrintDialog_ = /*#__PURE__*/function (_React$PureComponent) {
function HeightProfilePrintDialog_(props) {
var _this;
_classCallCheck(this, HeightProfilePrintDialog_);
_this = _callSuper(this, HeightProfilePrintDialog_, [props]);
_defineProperty(_this, "state", {
initialized: false,
imageUrl: ''
});
_defineProperty(_this, "closePrintWindow", function () {
_this.externalWindow.close();
});
_defineProperty(_this, "setWindowContent", function () {
_this.externalWindow.addEventListener('beforeunload', _this.props.onClose, false);
var container = _this.externalWindow.document.getElementById("heightprofilecontainer");
if (container) {
var printBtn = _this.externalWindow.document.createElement('div');
printBtn.id = "print";
printBtn.style.marginBottom = "1em";
printBtn.innerHTML = '<style type="text/css">@media print{ #print { display: none; }}</style>' + '<button onClick="(function(){window.print();})()">' + LocaleUtils.tr("heightprofile.print") + '</button>';
container.appendChild(printBtn);
_this.imageEl = _this.externalWindow.document.createElement('div');
_this.imageEl.id = 'map';
_this.imageEl.innerHTML = LocaleUtils.tr("heightprofile.loadingimage");
container.appendChild(_this.imageEl);
_this.portalEl = _this.externalWindow.document.createElement('div');
_this.portalEl.id = 'profile';
container.appendChild(_this.portalEl);
_this.setState({
initialized: true
});
_this.externalWindow.document.body.style.overflowX = 'hidden';
} else {
_this.externalWindow.document.body.innerHTML = "Broken template. An element with id=heightprofilecontainer must exist.";
}
});
_defineProperty(_this, "refreshImage", function () {
var measurement = _this.props.measurement;
var layer = {
type: 'vector',
opacity: 255,
features: [].concat(_toConsumableArray(measurement.coordinates.map(function (coord) {
return {
type: 'Feature',
geometry: {
coordinates: coord,
type: 'Point'
},
styleOptions: {
fillColor: [255, 255, 255, 1],
strokeColor: [255, 0, 0, 1],
strokeWidth: 2,
circleRadius: 6,
strokeDash: []
}
};
})), [{
type: 'Feature',
geometry: {
coordinates: measurement.coordinates,
type: 'LineString'
},
styleOptions: {
strokeColor: [255, 0, 0, 1],
strokeWidth: 4,
strokeDash: [],
headmarker: _this.props.measurement.lineHeadMarker,
tailmarker: _this.props.measurement.lineTailMarker
},
properties: {
segment_labels: measurement.segment_lengths.map(function (length) {
return MeasureUtils.formatMeasurement(length, false, measurement.lenUnit);
})
}
}])
};
var mapCrs = _this.props.map.projection;
var scale = Math.round(MapUtils.computeForZoom(_this.props.map.scales, _this.props.map.zoom));
var exportParams = LayerUtils.collectPrintParams(_this.props.layers, _this.props.theme, scale, mapCrs, true, false);
var highlightParams = VectorLayerUtils.createPrintHighlighParams([layer], mapCrs, scale);
var bounds = _toConsumableArray(_this.props.map.bbox.bounds);
if (CoordinatesUtils.getAxisOrder(_this.props.map.projection).substr(0, 2) === 'ne') {
bounds = [bounds[1], bounds[0], bounds[3], bounds[2]];
}
var imageParams = _objectSpread({
SERVICE: 'WMS',
VERSION: '1.3.0',
REQUEST: 'GetMap',
TRANSPARENT: 'true',
TILED: 'false',
CRS: _this.props.map.projection,
BBOX: bounds,
WIDTH: _this.props.map.size.width,
HEIGHT: _this.props.map.size.height,
HIGHLIGHT_GEOM: highlightParams.geoms.join(";"),
HIGHLIGHT_SYMBOL: highlightParams.styles.join(";"),
HIGHLIGHT_LABELSTRING: highlightParams.labels.join(";"),
HIGHLIGHT_LABELCOLOR: highlightParams.labelFillColors.join(";"),
HIGHLIGHT_LABELBUFFERCOLOR: highlightParams.labelOutlineColors.join(";"),
HIGHLIGHT_LABELBUFFERSIZE: highlightParams.labelOutlineSizes.join(";"),
HIGHLIGHT_LABELSIZE: highlightParams.labelSizes.join(";"),
HIGHLIGHT_LABEL_DISTANCE: highlightParams.labelDist.join(";"),
HIGHLIGHT_LABEL_ROTATION: highlightParams.labelRotations.join(";"),
csrf_token: MiscUtils.getCsrfToken()
}, exportParams);
var baseUrl = _this.props.theme.url.split("?")[0];
var query = Object.entries(imageParams).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
k = _ref2[0],
v = _ref2[1];
return "".concat(encodeURIComponent(k), "=").concat(encodeURIComponent(v));
}).join('&');
var src = baseUrl + "?" + query;
if (src === _this.state.imageUrl) {
return;
}
_this.setState({
imageUrl: src
});
var options = {
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
responseType: "blob"
};
axios.post(baseUrl, query, options).then(function (response) {
var reader = new FileReader();
reader.readAsDataURL(response.data);
reader.onload = function () {
_this.imageEl.innerHTML = "<img src=\"".concat(reader.result, "\" style=\"width: 100%\" />");
};
})["catch"](function () {
// Fall back to GET
_this.imageEl.innerHTML = "<img src=\"".concat(src, "\" style=\"width: 100%\" />");
});
});
_defineProperty(_this, "windowResized", function () {
if (_this.chart) {
_this.chart.resize();
}
});
_this.externalWindow = null;
_this.chart = null;
_this.portalEl = null;
_this.imageEl = null;
return _this;
}
_inherits(HeightProfilePrintDialog_, _React$PureComponent);
return _createClass(HeightProfilePrintDialog_, [{
key: "componentDidMount",
value: function componentDidMount() {
var templatePath = MiscUtils.resolveAssetsPath(this.props.templatePath);
this.externalWindow = window.open(templatePath, LocaleUtils.tr("heightprofile.title"), "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes");
// Inherit API
this.externalWindow.qwc2 = window.qwc2;
this.externalWindow.addEventListener('load', this.setWindowContent, false);
this.externalWindow.addEventListener('resize', this.windowResized, false);
window.addEventListener('beforeunload', this.closePrintWindow);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
if (this.props.layers !== prevProps.layers || this.props.map.bbox !== prevProps.map.bbox || this.state.initialized && !prevState.initialized) {
this.refreshImage();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.closePrintWindow();
window.removeEventListener('beforeunload', this.closePrintWindow);
}
}, {
key: "render",
value: function render() {
var _this2 = this;
if (!this.state.initialized) {
return null;
}
return /*#__PURE__*/ReactDOM.createPortal(this.props.children(function (el) {
_this2.chart = el;
}, false), this.portalEl);
}
}]);
}(React.PureComponent);
_defineProperty(HeightProfilePrintDialog_, "propTypes", {
children: PropTypes.func,
layers: PropTypes.array,
map: PropTypes.object,
measurement: PropTypes.object,
onClose: PropTypes.func,
templatePath: PropTypes.string,
theme: PropTypes.object
});
var HeightProfilePrintDialog = connect(function (state) {
return {
layers: state.layers.flat,
map: state.map,
theme: state.theme.current
};
}, {})(HeightProfilePrintDialog_);
/**
* Displays a height profile along a measured line.
*
* Triggered automatically when a line is measured via the `Measure` plugin.
*
* Requires `elevationServiceUrl` in `config.json` to point to a `qwc-elevation-service`,
* or a custom elevation interface to be exposed in `window.QWC2ElevationInterface`, see
* [ElevationInterface.js](https://github.com/qgis/qwc2/blob/master/utils/ElevationInterface.js).
*
* The print height profile functionality requires a template located by default at `assets/templates/heightprofileprint.html`
* with containing a container element with `id=heightprofilecontainer`.
*/
var HeightProfile = /*#__PURE__*/function (_React$Component) {
function HeightProfile(props) {
var _this3;
_classCallCheck(this, HeightProfile);
_this3 = _callSuper(this, HeightProfile, [props]);
_defineProperty(_this3, "state", {
data: {},
selectedDatasetIndices: [0],
reqId: null,
drawnodes: true,
printdialog: false
});
_defineProperty(_this3, "onClose", function () {
_this3.setState({
data: {},
isloading: false
});
_this3.props.changeMeasurementState(_objectSpread(_objectSpread({}, _this3.props.measurement), {}, {
pickPositionCallback: null
}));
});
_defineProperty(_this3, "renderHeightProfile", function (saveRef, interactive) {
var _this3$state$selected2;
if (_this3.props.measurement.drawing) {
return null;
}
if (_this3.state.data.error) {
return /*#__PURE__*/React.createElement("div", {
className: "height-profile-error"
}, LocaleUtils.tr("heightprofile.error") + ": " + _this3.state.data.error);
}
var distanceStr = LocaleUtils.tr("heightprofile.distance");
var heightStr = LocaleUtils.tr("heightprofile.height");
var aslStr = LocaleUtils.tr("heightprofile.asl");
var _this3$state$selected = _this3.state.selectedDatasetIndices,
selectedDatasetIndices = _this3$state$selected === void 0 ? [] : _this3$state$selected;
var datasets = selectedDatasetIndices.flatMap(function (idx) {
return [{
label: _this3.state.data[idx].dataset,
data: _this3.state.data[idx].y.map(function (y, i) {
return {
x: _this3.state.data[idx].x[i],
y: y
};
}),
fill: true,
backgroundColor: "rgba(255,0,0,0.5)",
borderColor: "rgb(255,0,0)",
borderWidth: 2,
pointRadius: 0,
order: 1
}, {
type: 'bubble',
data: _this3.state.data[idx].nodes,
backgroundColor: 'rgb(255, 255, 255)',
borderColor: 'rgb(255, 0, 0)',
borderWidth: 2,
radius: 5,
hoverRadius: 0,
hoverBorderWidth: 2,
order: 0,
hidden: !_this3.state.drawnodes
}];
});
var data = {
labels: _this3.state.data[0].x,
// X-axis labels are all the same
datasets: datasets
};
var sampleDataset = _this3.state.data[(_this3$state$selected2 = _this3.state.selectedDatasetIndices[0]) !== null && _this3$state$selected2 !== void 0 ? _this3$state$selected2 : 0]; // first selected dataset for chart scale etc.
// Approx 10 ticks
var stepSizeFact = Math.pow(10, Math.ceil(Math.log10(sampleDataset.totLength / 10)));
var stepSize = Math.round(sampleDataset.totLength / stepSizeFact) * stepSizeFact / 10;
var prec = _this3.props.heightProfilePrecision;
var options = {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 0
},
plugins: {
legend: {
display: false
},
tooltip: {
enabled: interactive,
intersect: false,
displayColors: false,
bodyFont: {
weight: 'bold'
},
callbacks: {
title: function title(ctx) {
return distanceStr + ": " + MeasureUtils.formatMeasurement(ctx[0].parsed.x, false, 'metric');
},
label: function label(ctx) {
return _this3.state.data.length > 1 ? "".concat(heightStr, " (").concat(ctx.dataset.label, "): ").concat(ctx.parsed.y.toFixed(prec), " m ").concat(aslStr) : "".concat(heightStr, ": ").concat(ctx.parsed.y.toFixed(prec), " m ").concat(aslStr);
}
}
}
},
scales: {
x: {
type: 'linear',
ticks: {
stepSize: stepSize,
font: {
size: 10
},
callback: function callback(value) {
return value;
}
},
title: {
display: true,
text: distanceStr + " [m]",
padding: 0
},
max: Math.ceil(sampleDataset.totLength)
},
y: {
ticks: {
font: {
size: 10
},
callback: function callback(value) {
return value.toFixed(prec);
}
},
title: {
display: true,
text: heightStr + " [m " + aslStr + "]"
},
max: Math.ceil(Math.max.apply(Math, _toConsumableArray(selectedDatasetIndices.map(function (idx) {
var _this3$state$data$idx;
return (_this3$state$data$idx = _this3.state.data[idx]) === null || _this3$state$data$idx === void 0 ? void 0 : _this3$state$data$idx.maxY;
})))),
min: Math.floor(Math.min.apply(Math, _toConsumableArray(selectedDatasetIndices.map(function (idx) {
var _this3$state$data$idx2;
return (_this3$state$data$idx2 = _this3.state.data[idx]) === null || _this3$state$data$idx2 === void 0 ? void 0 : _this3$state$data$idx2.minY;
}))))
}
},
onHover: interactive ? function (evt, activeEls, chart) {
var chartArea = chart.chartArea;
var chartX = Math.min(Math.max(evt.x - chartArea.left), chartArea.width);
_this3.updateMarker(chartX / chartArea.width * sampleDataset.totLength);
} : undefined
};
var datasetSelector = null;
if (interactive && _this3.state.data.length > 1) {
datasetSelector = /*#__PURE__*/React.createElement("div", {
className: "height-profile-dataset-select"
}, _this3.state.data.map(function (dataset, idx) {
var _this3$state$selected3;
var isSelected = (_this3$state$selected3 = _this3.state.selectedDatasetIndices) === null || _this3$state$selected3 === void 0 ? void 0 : _this3$state$selected3.includes(idx);
return /*#__PURE__*/React.createElement("div", {
key: "".concat(dataset.dataset, "-").concat(idx)
}, /*#__PURE__*/React.createElement(Icon, {
icon: isSelected ? "checked" : "unchecked",
onClick: function onClick() {
var selected = new Set(_this3.state.selectedDatasetIndices || []);
if (isSelected) {
selected["delete"](idx);
} else {
selected.add(idx);
}
_this3.setState({
selectedDatasetIndices: Array.from(selected)
});
}
}), /*#__PURE__*/React.createElement("span", null, dataset.dataset));
}));
}
return /*#__PURE__*/React.createElement("div", {
className: "height-profile-chart-container",
style: {
position: 'relative'
}
}, datasetSelector, /*#__PURE__*/React.createElement(Line, {
data: data,
options: options,
ref: saveRef
}));
});
_defineProperty(_this3, "resizeChart", function () {
if (_this3.chart) {
_this3.chart.resize();
}
});
_defineProperty(_this3, "updateMarker", function (x) {
var segmentLengths = _this3.props.measurement.segment_lengths;
var coo = _this3.props.measurement.coordinates;
if (isEmpty(segmentLengths) || isEmpty(coo)) {
return;
}
var i = 0;
var runl = 0;
while (i < segmentLengths.length - 1 && x > runl + segmentLengths[i]) {
runl += segmentLengths[i++];
}
var lambda = (x - runl) / segmentLengths[i];
var p = [coo[i][0] + lambda * (coo[i + 1][0] - coo[i][0]), coo[i][1] + lambda * (coo[i + 1][1] - coo[i][1])];
_this3.props.addMarker('heightprofile', p, '', _this3.props.projection, 1000001); // 1000001: one higher than the zIndex in MeasurementSupport...
});
_defineProperty(_this3, "showTooltip", function (idx) {
if (!_this3.chart) {
return;
}
var chartArea = _this3.chart.chartArea;
var activeElements = _this3.chart.data.datasets.map(function (ds, i) {
return {
ds: ds,
i: i
};
}).filter(function (_ref3) {
var ds = _ref3.ds;
return ds.type !== 'bubble';
}).map(function (_ref4) {
var i = _ref4.i;
return {
datasetIndex: i,
index: idx
};
});
_this3.chart.tooltip.setActiveElements(activeElements, {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2
});
_this3.chart.update();
});
_defineProperty(_this3, "clearMarkerAndTooltip", function () {
_this3.props.removeMarker('heightprofile');
if (_this3.chart) {
_this3.chart.tooltip.setActiveElements([], {
x: 0,
y: 0
});
}
});
_defineProperty(_this3, "pickPositionCallback", function (pos) {
var _this3$state$selected4;
if (!pos || isEmpty(_this3.state.data)) {
_this3.clearMarkerAndTooltip();
return;
}
var data = _this3.state.data[(_this3$state$selected4 = _this3.state.selectedDatasetIndices[0]) !== null && _this3$state$selected4 !== void 0 ? _this3$state$selected4 : 0];
// Find sample index
var segmentLengths = _this3.props.measurement.segment_lengths;
var coo = _this3.props.measurement.coordinates;
var x = 0;
for (var iSegment = 0; iSegment < coo.length - 1; ++iSegment) {
if (_this3.pointOnSegment(pos, coo[iSegment], coo[iSegment + 1])) {
var len = MeasureUtils.computeSegmentLengths([pos, coo[iSegment]], _this3.props.projection, _this3.props.measurement.geodesic)[0];
x += len;
break;
} else {
x += segmentLengths[iSegment];
}
}
var k = Math.min(1, x / data.totLength);
var idx = Math.min(data.y.length - 1, Math.floor(k * _this3.props.samples));
_this3.showTooltip(idx);
});
_defineProperty(_this3, "pointOnSegment", function (q, p1, p2) {
var tol = 1E-3;
// Determine whether points lie on same line: cross-product (P2-P1) x (Q - P1) zero?
var cross = (p2[0] - p1[0]) * (q[1] - p1[1]) - (q[0] - p1[0]) * (p2[1] - p1[1]);
if (Math.abs(cross) > tol) {
return false;
}
// Determine if coordinates lie within segment coordinates
if (Math.abs(p1[0] - p2[0]) > tol) {
return p1[0] <= q[0] && q[0] <= p2[0] || p2[0] <= q[0] && q[0] <= p1[0];
} else {
return p1[1] <= q[1] && q[1] <= p2[1] || p2[1] <= q[1] && q[1] <= p1[1];
}
});
_defineProperty(_this3, "exportProfile", function () {
// const data = this.state.data[this.state.selectedDatasetIndex];
_this3.state.selectedDatasetIndices.forEach(function (index) {
var data = _this3.state.data[index];
if (!data.x) {
return;
}
var csv = "";
csv += "index" + "\t" + "distance" + "\t" + "elevation" + "\n";
data.x.forEach(function (x, idx) {
var sample = {
x: x,
y: data.y[idx]
};
var prec = _this3.props.heightProfilePrecision;
var distance = Math.round(sample.x * Math.pow(10, prec)) / Math.pow(10, prec);
var height = Math.round(sample.y * Math.pow(10, prec)) / Math.pow(10, prec);
csv += String(idx).replace('"', '""') + "\t" + String(distance) + "\t" + String(height) + "\n";
});
FileSaver.saveAs(new Blob([csv], {
type: "text/plain;charset=utf-8"
}), _this3.state.data.length > 1 ? "heightprofile-".concat(data.dataset, ".csv") : "heightprofile.csv");
});
});
_this3.chart = null;
_this3.profilePrintWindow = null;
return _this3;
}
_inherits(HeightProfile, _React$Component);
return _createClass(HeightProfile, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.props.measurement.coordinates !== prevProps.measurement.coordinates) {
if (this.props.measurement.drawing === false && this.props.measurement.geomType === "LineString" && !isEmpty(this.props.measurement.coordinates)) {
this.queryElevations(this.props.measurement.coordinates, this.props.measurement.segment_lengths, this.props.projection);
} else if (!isEmpty(this.state.data)) {
this.setState({
data: {}
});
this.props.changeMeasurementState(_objectSpread(_objectSpread({}, this.props.measurement), {}, {
pickPositionCallback: null
}));
}
}
}
}, {
key: "queryElevations",
value: function queryElevations(coordinates, distances, projection) {
var _this4 = this;
var reqId = uuidv4();
this.setState({
reqId: reqId
});
var totLength = this.props.measurement.length;
getElevationInterface().getProfile(coordinates, distances, projection, this.props.samples).then(function (response) {
// Request changed
if (_this4.state.reqId !== reqId) {
return;
}
var elevationsList = response.list;
if (!elevationsList) {
elevationsList = [{
elevations: response,
dataset: null
}];
}
var data = elevationsList.map(function (entry, index) {
var elevations = entry.elevations;
// Compute x-axis distances and get node points
var nodes = [];
var cumDist = distances[0];
var distIdx = 0;
var y = elevations;
var x = y.map(function (value, idx, a) {
var dist = idx / (a.length - 1) * totLength;
if (dist >= cumDist) {
nodes.push({
x: dist,
y: y[idx]
});
cumDist += distances[++distIdx];
}
return dist;
});
// First and last node
nodes.unshift({
x: x[0],
y: y[0]
});
nodes.push({
x: x[x.length - 1],
y: y[y.length - 1]
});
var nonZeroElevations = elevations.filter(function (elev) {
return elev !== 0;
});
if (nonZeroElevations.length > 0) {
return {
dataset: entry.dataset || "".concat(LocaleUtils.tr("heightprofile.dhmdefaultname"), " ").concat(index + 1),
x: x,
y: elevations,
maxY: Math.max.apply(Math, _toConsumableArray(elevations)),
minY: Math.min.apply(Math, _toConsumableArray(nonZeroElevations)),
totLength: totLength,
nodes: nodes
};
}
return null;
}).filter(function (entry) {
return entry !== null;
});
_this4.setState(function (prevState) {
return {
reqId: null,
data: data,
selectedDatasetIndices: prevState.selectedDatasetIndices.filter(function (i) {
return i < data.length;
}) ? prevState.selectedDatasetIndices : [0]
};
});
_this4.props.changeMeasurementState(_objectSpread(_objectSpread({}, _this4.props.measurement), {}, {
pickPositionCallback: _this4.pickPositionCallback
}));
})["catch"](function (error) {
_this4.setState({
reqId: null,
data: error ? {
error: error
} : {}
});
});
}
}, {
key: "render",
value: function render() {
var _this5 = this;
if (isEmpty(this.state.data) && !this.state.isloading) {
return null;
}
var extraControls = [{
icon: 'circle',
active: this.state.drawnodes,
callback: function callback() {
return _this5.setState(function (state) {
return {
drawnodes: !state.drawnodes
};
});
},
title: LocaleUtils.tr("heightprofile.drawnodes")
}, {
icon: 'export',
callback: this.exportProfile,
title: LocaleUtils.tr("heightprofile.export")
}, {
icon: 'print',
active: this.state.printdialog,
callback: function callback() {
return _this5.setState(function (state) {
return {
printdialog: !state.printdialog
};
});
},
title: LocaleUtils.tr("heightprofile.print")
}];
return [/*#__PURE__*/React.createElement(ResizeableWindow, {
dockable: "bottom",
extraControls: extraControls,
icon: "line",
initialHeight: this.props.height,
initialWidth: 600,
initiallyDocked: true,
key: "ProfileDialog",
onClose: this.onClose,
onExternalWindowResized: this.resizeChart,
splitScreenWhenDocked: true,
title: LocaleUtils.tr("heightprofile.title"),
usePortal: false
}, this.state.isloading ? /*#__PURE__*/React.createElement("div", {
className: "height-profile-loading-indicator"
}, /*#__PURE__*/React.createElement(Spinner, {
className: "spinner"
}), " ", LocaleUtils.tr("heightprofile.loading")) : this.renderHeightProfile(function (el) {
_this5.chart = el;
}, true)), this.state.printdialog ? /*#__PURE__*/React.createElement(HeightProfilePrintDialog, {
key: "ProfilePrintDialog",
measurement: this.props.measurement,
onClose: function onClose() {
return _this5.setState({
printdialog: false
});
},
templatePath: this.props.templatePath
}, this.renderHeightProfile) : null];
}
}]);
}(React.Component);
_defineProperty(HeightProfile, "propTypes", {
addMarker: PropTypes.func,
changeMeasurementState: PropTypes.func,
/** The height of the height profile widget in pixels. */
height: PropTypes.number,
/** The precision of displayed and exported values (0: no decimals, 1: 1 decimal position, etc). */
heightProfilePrecision: PropTypes.number,
measurement: PropTypes.object,
projection: PropTypes.string,
removeMarker: PropTypes.func,
/** The number of elevation samples to query. */
samples: PropTypes.number,
/** Template location for the height profile print functionality */
templatePath: PropTypes.string
});
_defineProperty(HeightProfile, "defaultProps", {
samples: 500,
heightProfilePrecision: 0,
height: 150,
templatePath: ":/templates/heightprofileprint.html"
});
export default connect(function (state) {
return {
measurement: state.measurement,
projection: state.map.projection
};
}, {
addMarker: addMarker,
changeMeasurementState: changeMeasurementState,
removeMarker: removeMarker
})(HeightProfile);