UNPKG

@zpc_npm/vue-iclient-common

Version:

KQGIS iClient for Vue.js

1,447 lines (1,214 loc) 45.1 kB
/******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 1349: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { /* harmony import */ var element_plus_es__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2442); /* harmony import */ var element_plus_es__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(element_plus_es__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _init__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8945); /* harmony import */ var _init__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_init__WEBPACK_IMPORTED_MODULE_1__); element_plus_es__WEBPACK_IMPORTED_MODULE_0__.ElMessage.install = (Vue, opts) => { _init__WEBPACK_IMPORTED_MODULE_1___default()(Vue, opts); Vue.component("KqMessage", element_plus_es__WEBPACK_IMPORTED_MODULE_0__.ElMessage); }; /* harmony default export */ __webpack_exports__["default"] = (element_plus_es__WEBPACK_IMPORTED_MODULE_0__.ElMessage); /***/ }), /***/ 2442: /***/ (function(module) { module.exports = require("element-plus/es"); /***/ }), /***/ 8945: /***/ (function(module) { module.exports = require("@zpc_npm/vue-iclient-common/init.js"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ !function() { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function() { return module['default']; } : /******/ function() { return module; }; /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /******/ }(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ !function() { /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ }(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. !function() { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "addClass": function() { return /* binding */ addClass; }, "bind": function() { return /* binding */ bind; }, "clearNumberComma": function() { return /* binding */ clearNumberComma; }, "convertXY": function() { return /* binding */ convertXY; }, "createBodyBycoord": function() { return /* binding */ createBodyBycoord; }, "createRectByPoint": function() { return /* binding */ createRectByPoint; }, "createTxtBody": function() { return /* binding */ createTxtBody; }, "exportExcel": function() { return /* binding */ exportExcel; }, "exportSHP": function() { return /* binding */ exportSHP; }, "exportTXT": function() { return /* binding */ exportTXT; }, "featureCollection2GeometryCollection": function() { return /* binding */ featureCollection2GeometryCollection; }, "filterInvalidData": function() { return /* binding */ filterInvalidData; }, "formatKQMapInfo": function() { return /* binding */ formatKQMapInfo; }, "getDataType": function() { return /* binding */ getDataType; }, "getDateTime": function() { return /* binding */ getDateTime; }, "getKQURLFromURL": function() { return /* binding */ getKQURLFromURL; }, "getLayerZIndex": function() { return /* binding */ getLayerZIndex; }, "getValueCaseInsensitive": function() { return /* binding */ getValueCaseInsensitive; }, "handleDataParentRes": function() { return /* binding */ handleDataParentRes; }, "handleWithCredentials": function() { return /* binding */ handleWithCredentials; }, "hexToRgba": function() { return /* binding */ hexToRgba; }, "isDate": function() { return /* binding */ isDate; }, "isMatchUrl": function() { return /* binding */ isMatchUrl; }, "isNumber": function() { return /* binding */ isNumber; }, "isTransparent": function() { return /* binding */ isTransparent; }, "objectWithoutProperties": function() { return /* binding */ objectWithoutProperties; }, "parseUrl": function() { return /* binding */ parseUrl; }, "readExcel": function() { return /* binding */ readExcel; }, "readJSON": function() { return /* binding */ readJSON; }, "readTxT": function() { return /* binding */ readTxT; }, "removeCPointFromCoordinates": function() { return /* binding */ removeCPointFromCoordinates; }, "removeClass": function() { return /* binding */ removeClass; }, "reservedDecimal": function() { return /* binding */ reservedDecimal; }, "updatePosition": function() { return /* binding */ updatePosition; }, "uploadSHP": function() { return /* binding */ uploadSHP; }, "urlAppend": function() { return /* binding */ urlAppend; } }); ;// CONCATENATED MODULE: external "core-js/modules/es.array.includes.js" var es_array_includes_js_namespaceObject = require("core-js/modules/es.array.includes.js"); // EXTERNAL MODULE: ./src/common/_ui/message/index.js var message = __webpack_require__(1349); ;// CONCATENATED MODULE: external "@zpc_npm/vue-iclient-common/_lang/index.js" var index_js_namespaceObject = require("@zpc_npm/vue-iclient-common/_lang/index.js"); ;// CONCATENATED MODULE: external "colorcolor" var external_colorcolor_namespaceObject = require("colorcolor"); var external_colorcolor_default = /*#__PURE__*/__webpack_require__.n(external_colorcolor_namespaceObject); ;// CONCATENATED MODULE: external "xlsx" var external_xlsx_namespaceObject = require("xlsx"); ;// CONCATENATED MODULE: external "omit.js" var external_omit_js_namespaceObject = require("omit.js"); var external_omit_js_default = /*#__PURE__*/__webpack_require__.n(external_omit_js_namespaceObject); ;// CONCATENATED MODULE: external "vue" var external_vue_namespaceObject = require("vue"); ;// CONCATENATED MODULE: external "xe-utils" var external_xe_utils_namespaceObject = require("xe-utils"); var external_xe_utils_default = /*#__PURE__*/__webpack_require__.n(external_xe_utils_namespaceObject); ;// CONCATENATED MODULE: ./src/common/_utils/util.js // 获取当前时间返回置顶格式 function getDateTime(timeType) { return (0,index_js_namespaceObject.geti18n)().d(new Date(), timeType.replace(/\+/g, "_"), (0,index_js_namespaceObject.getLanguage)()); } // hex -> rgba function hexToRgba(hex, opacity) { return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")"; } function isTransparent(color) { const rgba = external_colorcolor_default()(color, "rgba"); return +rgba.match(/(\d(\.\d+)?)+/g)[3] === 0; } // 保留指定位数的小数 function reservedDecimal(val, precise) { return Number(val).toFixed(precise); } // 清除数字(字符串型的)的逗号 function clearNumberComma(num) { if (num.replace) { num = num.replace(/,/g, ""); } return num; } function parseUrl(url) { const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/; return url.match(urlRe); } function getDataType(data) { return Object.prototype.toString.call(data); } // 判断输入的地址是否符合地址格式 function isMatchUrl(str) { let reg = new RegExp("(https?|http|file|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"); return reg.test(str); } // 判断是否为日期 function isDate(data) { let reg = /((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)$))/gi; return reg.test(data); } // 判断是否为数值 function isNumber(data) { let mdata = Number(data); if (mdata === 0) { return true; } return !isNaN(mdata); } function getValueCaseInsensitive(properties, searchKey) { const isObj = getDataType(properties) === "[object Object]"; if (!searchKey || !isObj) { return ""; } const lowerSearchKey = searchKey.toLocaleLowerCase(); for (let key in properties) { if (key.toLocaleLowerCase() === lowerSearchKey) { return properties[key]; } } return ""; } function filterInvalidData(datasetOptions, features) { const xFields = datasetOptions.map(item => item.xField); const yFields = datasetOptions.map(item => item.yField); const nextFeatures = features.filter(feature => { const matchXField = xFields.find(item => Object.prototype.hasOwnProperty.call(feature.properties, item)); const matchYField = yFields.find(item => ![undefined, null, ""].includes(feature.properties[item])); return !!(matchXField && matchYField); }); return nextFeatures; } function handleWithCredentials(url, iportalServiceProxyUrl, defaultValue = false) { if (!iportalServiceProxyUrl) { return defaultValue; } return url.indexOf(iportalServiceProxyUrl) >= 0 || defaultValue; } function handleDataParentRes(url, parentResId, parentResType = "DATA") { if (!parentResId) { return url; } return urlAppend(url, `parentResType=${parentResType}&parentResId=${parentResId}`); } function urlAppend(url, paramStr) { let newUrl = url; if (paramStr) { if (paramStr.indexOf("?") === 0) { paramStr = paramStr.substring(1); } let parts = (url + " ").split(/[?&]/); newUrl += parts.pop() === " " ? paramStr : parts.length ? "&" + paramStr : "?" + paramStr; } return newUrl; } function objectWithoutProperties(obj, omitKeys = []) { return external_omit_js_default()(obj, omitKeys); } let zIndex = 200; function getLayerZIndex() { return zIndex; } /** * 处理kq的地图服务原数据信息 */ function formatKQMapInfo(mapinfo, serviceUrl, serviceId, accessToken, defaultShowLayerNames, isShowAllLayers) { let lods = mapinfo.tileInfo.lods; let resolutions = []; let scale = []; let minZoom = 0; let maxZoom = lods.length - 1; let center = getMapCenter(); let bounds84 = [[mapinfo.rect84.miny, mapinfo.rect84.minx], [mapinfo.rect84.maxy, mapinfo.rect84.maxx]]; let origin = [mapinfo.tileInfo.origin.x, mapinfo.tileInfo.origin.y]; lods.forEach(item => { resolutions.push(item.resolution); scale.push(item.scale); }); if (mapinfo.spatialReference.epsg === 910111 || mapinfo.spatialReference.epsg === 910112) { mapinfo.spatialReference.epsg = 3857; } else if (mapinfo.spatialReference.epsg === 910101 || mapinfo.spatialReference.epsg === 910102) { mapinfo.spatialReference.epsg = 4326; } let treeData = []; let _layers = []; let layers_show = []; let _layers_old = JSON.parse(JSON.stringify(mapinfo.layers)); createLayerTree(treeData); resetTreeData(treeData, _layers); // 修改顺序 要和服务一致 for (let i = 0; i < _layers.length; i++) { _layers[i].zIndex = zIndex++; _layers[i].zIndex_old = _layers[i].zIndex; _layers[i].srs_service = mapinfo.spatialReference; layers_show.push(_layers[i]); } // 根据id排序 layers_show.sort(function (a, b) { let value1 = a["id"]; let value2 = b["id"]; return value1 - value2; }); return { spatialReference: mapinfo.spatialReference, // 空间参考 rect: mapinfo.rect, //服务范围 rect84: mapinfo.rect84, //服务范围转4326 layers_old: _layers_old, //服务元数据中的layers layers_show, //服务需要显示的图层 去掉图层组、融合图层的子图层 layerTreeData: treeData, //树结构的图层数据 center, //中心点 bounds84, //4326的bounds resolutions, //分辨率 scale, //比例尺 minZoom, //最小级别 maxZoom, //最大级别 origin //原点坐标 }; function getMapCenter() { return [(mapinfo.rect84.miny + mapinfo.rect84.maxy) / 2, (mapinfo.rect84.minx + mapinfo.rect84.maxx) / 2]; } /** * 根据属性parentLayerId 处理数据生成树结构 */ function createLayerTree(treedata) { let layers = mapinfo.layers; let _ids = []; for (let i = 0; i < layers.length; i++) { reformattedIcon(layers[i]); if (layers[i].parentLayerId === -1) { treedata.push(layers[i]); _ids.push(i); } } for (let z = _ids.length - 1; z >= 0; z--) { layers.splice(_ids[z], 1); } if (layers.length > 0) { getChildren(layers, treedata); } } function getChildren(parentlayers, treedata) { let i, z; for (z = 0; z < treedata.length; z++) { let _ids = []; let children = []; for (i = 0; i < parentlayers.length; i++) { if (parentlayers[i].parentLayerId === treedata[z].id) { children.push(parentlayers[i]); _ids.push(i); } } for (let i = _ids.length - 1; i >= 0; i--) { parentlayers.splice(_ids[i], 1); } if (children.length > 0) { treedata[z].children = children; } else { continue; } if (parentlayers.length > 0) { getChildren(parentlayers, treedata[z].children); } else { break; } } } /** * 去除树数据中融合图层子节点 */ function resetTreeData(data, layers) { for (let i = data.length - 1; i >= 0; i--) { let children = data[i].children; if (children) { // 融合图层 if (!data[i].combined) { resetTreeData(data[i].children, layers); } else { delete data[i].children; // 补充图层信息 setLayerInfo(data[i]); layers.push(data[i]); } } else { // 是分组文件夹且不是融合图层且没有子图层的时候 就是空文件夹 if (!(data[i].groupLayer && !data[i].combined)) { setLayerInfo(data[i]); // 标记图层类型 layers.push(data[i]); } } } } // 格式化图标样式 function reformattedIcon(layer) { if (layer.shapeType === "point") { layer.Icon = layer.Icon || "el-icon-copy-document"; } else if (layer.shapeType === "polyline") { layer.Icon = layer.Icon || "el-icon-set-up"; } else if (layer.shapeType === "polygon") { layer.Icon = layer.Icon || "el-icon-baseball"; } else if (layer.layerType === "yx") { layer.Icon = layer.Icon || "el-icon-picture-outline"; } else { layer.Icon = layer.Icon || "el-icon-copy-document"; } } function setLayerInfo(layer) { layer.serverType = "kqserver"; // 服务信息返回的url是服务器本机的ip合端口 实际使用过程中可能会用到映射的ip合端口 layer.url = serviceUrl; if (layer.url.substring(layer.url.length - 1) !== "/") { layer.url += "/"; } layer.url += serviceId + "/map"; layer.accessToken = accessToken; // 默认有visible属性 但是值是true layer.visible = getLayerDefaultState(layer); } // 设置图层默认值 function getLayerDefaultState(layer) { // 默认勾选参数为空时 以参数isShowAllLayers为准 if (!defaultShowLayerNames || defaultShowLayerNames.length === 0) { return isShowAllLayers; } else { let hasId = false; for (let i = 0; i < defaultShowLayerNames.length; i++) { if (layer.guid === defaultShowLayerNames[i] || layer.name === defaultShowLayerNames[i]) { hasId = true; break; } } return hasId; } } } /** * 上传解析shp文件 * @serverUrl 服务url * @file 上传file文件流 * @ua_token 微服务版本token */ function uploadSHP(serverUrl, file, ua_token, callbakFun) { let params = new KqGIS.GeometryAnalysis.ShpParserParams({ file: file }); new KqGIS.GeometryAnalysis.ShpParserService(serverUrl + "?ua_token=" + ua_token, { eventListeners: { processCompleted: response => { const result = response.result; console.log(result); if (result.resultcode === "success") { callbakFun(result.result[0]); } else { callbakFun(); } }, processFailed: () => { callbakFun(); } } }).processAsync(params); } /** * 解析json 文件 * @file 上传file文件流 * @callbackFun 回调方法 传入解析后的features数组 */ function readJSON(file, callbackFun) { let readEncoding = "utf-8"; let reader = new FileReader(); reader.readAsText(file, readEncoding); reader.onload = function () { callbackFun(JSON.parse(this.result)); }; } /** * 解析txt文件 * @file 上传file文件流 * @callbackFun 回调方法 传入解析后的features数组 */ function readTxT(file, callbackFun) { let readEncoding = "utf-8"; let reader = new FileReader(); reader.onload = function () { let vss = this.result; vss = vss.replace(new RegExp("\t", "g"), ""); let rows = vss.split("\r\n"); // 根据换行切割内容 // txt导入部发格式,编码不是utf-8的时候,中文是乱码,用另外的编码再次读取 if (rows[0].indexOf("[") === 0 && rows[0].indexOf("]") > -1 && rows[0].indexOf("属性描述") === -1) { if (readEncoding !== "gb18030") { readEncoding = "gb18030"; reader.readAsText(file, readEncoding); } else { (0,message["default"])({ message: "导入TxT文件失败,请检查文件格式!", type: "error", duration: 2000 }); callbackFun(null); console.log(vss); } return; } let geoType; // 地块类型 let dataArr = []; // 地块数组 let objarr = []; // 多边形数组 let pointArr = []; // 一个多边形的点数组 let isHead = true; // 是否表头 for (let k in rows) { let nextIndex = Number(k) + 1; // 下行的索引值,for循环这样写的时候key不是number类型,必须转换 // 暂时表头部分不解析 if (isHead && typeof rows[nextIndex] !== "undefined" && rows[nextIndex].indexOf("@") !== -1) { isHead = false; continue; } if (isHead) { continue; } let row = rows[k]; if (typeof row === "undefined" || row === "") { // 最后行空行时 要加上数组 if (Number(k) === rows.length - 1) { dataArr.push({ type: geoType, coordinates: objarr }); } continue; } let arr_row = row.split(","); // 行中如果有'@',标识是一个新的地块,解析地块信息,暂时只解析了类型 if (row.indexOf("@") !== -1) { if (arr_row[4] === "点") { geoType = "Point"; } else if (arr_row[4] === "线") { geoType = "LineString"; } else if (arr_row[4] === "面" || arr_row[6] === "面") { geoType = "Polygon"; } pointArr = new Array(); objarr = new Array(); continue; } pointArr.push([Number(arr_row[3]), Number(arr_row[2])]); if (Number(k) < rows.length - 1) { // 下一行数据判断 if (rows[nextIndex].indexOf("@") !== -1) { // 结束上个地块 getCoor(geoType, pointArr, objarr); dataArr.push({ type: geoType, coordinates: objarr }); } else { let nextRow = rows[nextIndex].split(","); if (nextRow.length > 0) { if (nextRow[1] !== arr_row[1]) { // 一行的第二个值是代表圈号,圈号不同表示不同的多边形 getCoor(geoType, pointArr, objarr); pointArr = []; } } } } else { // 最后的行需要加上多边形 getCoor(geoType, pointArr, objarr); dataArr.push({ type: geoType, coordinates: objarr }); } } // 地图和服务默认投影都是经纬度的,传入定位的坐标也必须是经纬度的,需要转换 if (dataArr.length === 0) { (0,message["default"])({ message: "导入TxT文件失败,请检查文件格式!", type: "error", duration: 2000 }); callbackFun(null); return; } let features = []; for (let d in dataArr) { let f = dataArr[d]; // 坐标转换 projToWGS1984(f); let feature = { type: "Feature", geometry: f }; features.push(feature); } let data = { type: "FeatureCollection", features: features }; if (callbackFun) { callbackFun(data); } }; reader.readAsText(file, "utf-8"); function getCoor(type, pointArr, objarr) { if (type === "Point") { objarr.push(pointArr[0][0]); objarr.push(pointArr[0][1]); } else if (type === "LineString") { for (let i = 0; i < pointArr.length; i++) { objarr.push(pointArr[i]); } } else if (type === "Polygon") { objarr.push(pointArr); } } } /** * 解析excel文件 * @file 上传file文件流 * @callbackFun 回调方法 传入解析后的features数组 */ function readExcel(file) { // 通过FileReader对象读取文件 const fileReader = new FileReader(); fileReader.onload = event => { try { const { result } = event.target; // 以二进制流方式读取得到整份excel表格对象 const workbook = external_xlsx_namespaceObject.read(result, { type: "binary" }); // 存储获取到的数据 let persons = []; // 遍历每张工作表进行读取(这里默认只读取第一张表) for (const sheet in workbook.Sheets) { // esline-disable-next-line if (workbook.Sheets.hasOwnProperty(sheet)) { // 利用 sheet_to_json 方法将 excel 转成 json 数据 persons = persons.concat(external_xlsx_namespaceObject.utils.sheet_to_json(workbook.Sheets[sheet])); // break; // 如果只取第一张表,就取消注释这行 } } let dataArr = []; // 地块数组 let objarr = []; // 多边形数组 let pointArr = []; // 一个多边形的点数组 objarr.push(pointArr); dataArr.push({ type: "Polygon", coordinates: objarr }); for (let k = 0; k < persons.length; k++) { pointArr.push([Number(persons[k]["纵坐标(X)"]), Number(persons[k]["横坐标(Y)"])]); if (persons[k]["操作符"] === "D") { dataArr = []; objarr = []; objarr.push(pointArr); dataArr.push({ type: "Polygon", coordinates: objarr }); } } // 删除空行的数据 if (dataArr[dataArr.length - 1]["coordinates"][0].length === 0) { dataArr.splice(dataArr.length - 1, 1); } let features = []; for (let d = 0; d < dataArr.length; d++) { let f = dataArr[d]; // 坐标转换 projToWGS1984(f); let feature = { type: "Feature", geometry: f }; features.push(feature); } let data = { type: "FeatureCollection", features: features }; if (callbackFun) { callbackFun(data); } } catch (e) { (0,message["default"])({ message: "导入过程出错!", type: "error" }); console.log(e); } }; // 以二进制方式打开文件 fileReader.readAsBinaryString(file); } /** * 坐标转换成WGS1984 WGS1984是内部默认投影 * @param geometry GeoJson标准格式的geomerty对象 */ function projToWGS1984(geometry) { let inPrj = getGeoEPSGByFeture(geometry); let outPrj = "EPSG:4326"; // 转换的投影 let transform = proj4(outPrj, inPrj); let type = geometry.type; let coor = geometry.coordinates; let d, c, p, newPoint; if (type === "Polygon") { if (coor[0][0][0].toString().indexOf(".") === 3) { // 经纬度坐标不转 return; } for (d in coor) { c = coor[d]; // if (!$.isArray(c)) { // continue; // } for (p in c) { newPoint = transform.inverse([Number(c[p][0]), Number(c[p][1])]); console.log(c[p], newPoint); c[p] = newPoint; } } } else if (type === "MultiPolygon") { if (coor[0][0][0][0].toString().indexOf(".") === 3) { // 经纬度坐标不转 return; } for (let r = 0; r < coor.length; r++) { let _coor = coor[r]; for (d in _coor) { c = _coor[d]; // if (!$.isArray(c)) { // continue; // } for (p in c) { newPoint = transform.inverse([Number(c[p][0]), Number(c[p][1])]); c[p] = newPoint; } } } } else if (type === "LineString") { if (coor[0][0].toString().indexOf(".") === 3) { // 经纬度坐标不转 return; } for (d in coor) { newPoint = transform.inverse(coor[d]); coor[d] = newPoint; } } else if (type === "Point") { if (coor[0].toString().indexOf(".") === 3) { // 经纬度坐标不转 return; } coor = transform.inverse(coor); } // 根据geometry对象 获取图形的空间参考 返回proj4格式 只支持4490 function getGeoEPSGByFeture(geometry) { let _x = 0; if (geometry.type.toUpperCase() === "POLYGON") { _x = geometry.coordinates[0][0][0] || geometry.coordinates[0][0]; } else if (geometry.type.toUpperCase() === "MULTIPOLYGON") { _x = geometry.coordinates[0][0][0][0] || geometry.coordinates[0][0][0]; } else if (geometry.type.toUpperCase() === "POINT") { _x = geometry.coordinates[0][0] || geometry.coordinates[0]; } else { return "+proj=tmerc +lat_0=0 +lon_0=99 +k=1 +x_0=33500000 +y_0=0 +ellps=GRS80 +units=m +no_defs "; } let dh = _x.toString().substr(0, 2); const _dh = 33; // 以33度带为计算点 let lon = 99; // 以33度带为计算点 let x = 33500000; // 以33度带为计算点 lon = lon + (Number(dh) - _dh) * 3; x = x + (Number(dh) - _dh) * 1000000; let a = `+proj=tmerc +lat_0=0 +lon_0=${lon} +k=1 +x_0=${x} +y_0=0 +ellps=GRS80 +units=m +no_defs `; return a; } } /** * 导出 Excel * @tableData 表格数据 数组对象 * @fields 表格数据中的属性名称 * @fields_alias 表格数据中的属性名称对应的显示别名 * @fileName 导出的文件名 */ function exportExcel(tableData, fields, fields_alias, fileName) { let tableHtml = '<table border="1" style="text-align:left">'; tableHtml += "<thead>"; tableHtml += '<tr style="height:40px;">'; for (let f = 0; f < fields_alias.length; f++) { tableHtml += '<th style="background:#80C3E3;">' + fields_alias[f] + "</th>"; } tableHtml += "</tr>"; tableHtml += "</thead>"; tableHtml += "<tbody>"; if (fields && fields.length) { tableData.forEach((item, index) => { tableHtml += '<tr style="height:30px;">'; for (let f = 0; f < fields.length; f++) { tableHtml += "<td>" + item[fields[f]] + "</td>"; } tableHtml += "</tr>"; }); } else { tableHtml += '<tr style="height:30px;">'; tableData.forEach((item, index) => { tableHtml += "<td>" + item.value + "</td>"; }); } tableHtml += "</tbody>"; tableHtml += "</table>"; expExcel(tableHtml, fileName); function expExcel(tableHtml, fileName) { let excelFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' + 'xmlns="http://www.w3.org/TR/REC-html40">'; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'; excelFile += "<head>"; excelFile += "<xml>"; excelFile += "<x:ExcelWorkbook>"; excelFile += "<x:ExcelWorksheets>"; excelFile += "<x:ExcelWorksheet>"; excelFile += "<x:Name>导出结果</x:Name>"; excelFile += "<x:WorksheetOptions>"; excelFile += "<x:DisplayGridlines/>"; excelFile += "</x:WorksheetOptions>"; excelFile += "</x:ExcelWorksheet>"; excelFile += "</x:ExcelWorksheets>"; excelFile += "</x:ExcelWorkbook>"; excelFile += "</xml>"; excelFile += "</head>"; excelFile += "<body>"; excelFile += tableHtml; excelFile += "</body>"; excelFile += "</html>"; let url = "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(excelFile); let anchor = document.createElement("a"); anchor.href = url; anchor.id = "loadExcel"; anchor.style = "visibility:hidden"; anchor.download = fileName + ".xls"; document.body.appendChild(anchor); anchor.click(); document.body.removeChild(anchor); } } /** * 导出shp * @ServerUrl kq服务的URL 通用geometry服务 不要服务名 http://{IP:PORT}/{KQGis}/rest/services * @featureCollection GeoJSON格式的FeatureCollection对象 不是字符串 */ function exportSHP(ServerUrl, ListData) { let url = ServerUrl; var expFeatureCollection = { type: "FeatureCollection", features: [] }; for (var i = 0; i < ListData.length; i++) { let features = ListData[i]; expFeatureCollection["features"].push(features); } // let geojson = { data: JSON.stringify(expFeatureCollection), geoSRS: "EPSG:4326" }; // window.KqGIS.ExportShape.getInstance().exportShapeAsync({ // geojson: geojson, // url: ServerUrl, // function() { // console.log(ServerUrl); // } // }); let params = new KqGIS.GeometryAnalysis.ShpExportParams({ data: JSON.stringify(expFeatureCollection), geoSRS: new KqGIS.ServiceSRS({ type: "EPSG", value: "4326" }) }); new KqGIS.GeometryAnalysis.ShpExportService(ServerUrl, { eventListeners: { processCompleted: response => { const result = response.result; if (result.resultcode === "success") { const _url = result.url; const exporturl = ServerUrl.substring(0, ServerUrl.indexOf("/rest")) + _url.substring(_url.indexOf("/download")); const elink = document.createElement("a"); elink.href = exporturl; elink.setAttribute("download", "shapefile.zip"); elink.style.display = "none"; document.body.appendChild(elink); setTimeout(() => { elink.click(); document.body.removeChild(elink); }, 100); } }, processFailed: () => {} } }).processAsync(params); } /** * 去除坐标重点 geojson格式中的coordinates三维数组 * @param coordinates */ function removeCPointFromCoordinates(coordinates) { for (let i = 0; i < coordinates.length; i++) { let points = coordinates[i]; for (let m = points.length - 2; m >= 0; m--) { let p = points[m]; let q = points[m + 1]; if (p[0] === q[0] && p[1] === q[1]) { points.splice(m + 1, 1); } } } } // 导出txt方法--总方法 function createTxtBody(features) { let txtBodys = ""; for (let k in features) { let geometry = features[k]["geometry"]; let geoType = geometry["type"]; let coordinates = geometry["coordinates"]; // let RKZQBM = features[k]['properties']['XZQDM'] === undefined ? '' : features[k]['properties']['XZQDM']; // let ZQMC = features[k]['properties']['XZQMC'] === undefined ? '' : features[k]['properties']['XZQDM']; switch (geoType) { case "Point": txtBodys += createBodyBycoord([[coordinates]], "", "", "点"); break; case "LineString": // this.removeCPointFromCoordinates(coordinates); txtBodys += createBodyBycoord([coordinates], "", "", "线"); break; case "Polygon": removeCPointFromCoordinates(coordinates); txtBodys += createBodyBycoord(coordinates, "", "", ""); break; case "MultiPolygon": for (var i = 0; i < coordinates.length; i++) { removeCPointFromCoordinates(coordinates[i]); txtBodys += createBodyBycoord(coordinates[i], "", "", ""); } break; } } return txtBodys; } function createBodyBycoord(_coordinates, RKZQBM, ZQMC, YTDKBH) { let geoNtype = "面"; let pCcount = 0; let value = ""; // 点序号 let startIndex = 0; // 环的起始点序号 let txtBodys = ""; for (let i = 0; i < _coordinates.length; i++) { let points = _coordinates[i]; // 坐标面积小于1时 忽略图形 //let area = this.getAreaByPionts(points); //if (area < 1 && YTDKBH != "线" && points.length > 2) { // if (YTDKBH != "线" && points.length > 2) { // continue; // } for (let p = 0; p < points.length; p++) { if (p === 0) { startIndex = pCcount; } let index; if (p === points.length - 1) { index = startIndex; } else { index = pCcount; pCcount++; } value += "J" + (index + 1) + "," + ( // 点序号,闭合点的序号和起点一样 i + 1) + "," + Math.round(Number(points[p][1]) * 10000) / 10000 + "," + Math.round(Number(points[p][0]) * 10000) / 10000 + " \r\n"; } } // if (pCcount > 0 || ) { txtBodys += pCcount + ",," + RKZQBM + "," + ZQMC + "," + YTDKBH + ",," + geoNtype + ",,,,@\r\n" + value; // } return txtBodys; } /** * 保存文件方法 * @value 内容 字符串 * @type 类型 传null * @name 下载名称 */ function exportTXT(value, type, name) { type = type || "text/plain;charset=utf-8"; let blob; if (typeof window.Blob === "function") { blob = new Blob([value], { type: type }); } else { let BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder; let bb = new BlobBuilder(); bb.append(value); blob = bb.getBlob(type); } let URL = window.URL || window.webkitURL; let bloburl = URL.createObjectURL(blob); let anchor = document.createElement("a"); if ("download" in anchor) { anchor.style.visibility = "hidden"; anchor.href = bloburl; anchor.download = name; document.body.appendChild(anchor); let evt = document.createEvent("MouseEvents"); evt.initEvent("click", true, true); anchor.dispatchEvent(evt); document.body.removeChild(anchor); } else if (navigator.msSaveBlob) { navigator.msSaveBlob(blob, name); } else { location.href = bloburl; } } /** * 重整URL地址成kq api需要传入的地址 * 去掉map、去掉?后面的内容 */ function getKQURLFromURL(_URL) { let URL = _URL.indexOf("?") > -1 ? _URL.substring(0, _URL.indexOf("?")) : _URL; URL = URL.indexOf("/map") > -1 ? URL.substring(0, URL.indexOf("/map")) : URL; return URL; } // geojson格式的FeatureCollection格式转GeometryCollection格式 function featureCollection2GeometryCollection(featureCollection) { let features = featureCollection.features; let geometries = []; for (let i = 0; i < features.length; i++) { geometries.push(features[i].geometry); } return { type: "GeometryCollection", geometries: geometries }; } // export default function guid() { // return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { // var r = (Math.random() * 16) | 0, // v = c == "x" ? r : (r & 0x3) | 0x8; // return v.toString(16); // }); // } // 经纬度转度分秒 function convertXY(val) { if (!val) { return ""; } // 度=经纬度的整数部分 let d = Math.floor(Number(val)); // 经纬度的小数部分*60 let temp1 = (Number(val) - Number(d)) * 60; // 分=(经纬度的小数部分*60)的整数部分 let f = Math.floor(Number(temp1)); // 秒=(经纬度的小数部分*60-分)*60 let m = Math.floor((Number(temp1) - Number(f)) * 60); return d + "°" + f + "′" + m + "″"; } /** * @description 向node节点添加class * @param {Object} target - 目标 dom 元素 * @param {string} newClass - 要添加的class * @param {boolean} [isUnshift=false] - class是否要添加到最前面;默认false,添加到最后 */ function addClass(target, newClass, isUnshift = false) { var attrArr = target.getAttribute("class").split(" "); if (isUnshift) { attrArr.unshift(newClass); } else { attrArr.push(newClass); } target.setAttribute("class", attrArr.join(" ")); } /** * @description 删除node节点中的class * @param {Object} target - 目标 dom 元素 * @param {string} oldClass - 要删除的class */ function removeClass(target, oldClass) { var attrArr = target.getAttribute("class").split(" "); if (typeof oldClass === "string") { attrArr.forEach((item, index) => { if (item === oldClass) { attrArr.splice(index, 1); } }); } else { attrArr.forEach((item, index) => { oldClass.forEach((classItem, idx) => { if (item === classItem) { attrArr.splice(index, 1); } }); }); } target.setAttribute("class", attrArr.join(" ")); } /** * @description 计算组件位置,position 支持的格式为:"center","topLeft","topRight","bottomLeft","bottomRight", "topCenter", "bottomCenter" {top:'16px',left:'16px'}, {top:16,left:16} * @param {Object} boxElem - 组件容器 dom 元素 * @param {Object} props - 组件参数 */ const updatePosition = (boxElem, props) => { return (0,external_vue_namespaceObject.nextTick)().then(() => { const { position } = props; let _fixed = "static"; if (position) { _fixed = "absolute"; } else { return false; } addClass(boxElem, "is-absolute"); const clientVisibleWidth = _fixed === "fixed" ? document.documentElement.clientWidth || document.body.clientWidth : "auto"; const clientVisibleHeight = _fixed === "fixed" ? document.documentElement.clientHeight || document.body.clientHeight : "auto"; const isPosCenter = position === "center"; const { top, left, bottom, right } = external_xe_utils_default().isString(position) ? { top: position, left: position, bottom: position, right: position } : Object.assign({}, position); const topCenter = isPosCenter || top === "center"; const leftCenter = isPosCenter || left === "center"; const bottomCenter = isPosCenter || bottom === "center"; const rightCenter = isPosCenter || right === "center"; let posTop = ""; let posLeft = ""; let posBottom = ""; let posRight = ""; if (left && !leftCenter) { posLeft = isNaN(left) ? left : `${left}px`; } else { if (right && !rightCenter) { posRight = isNaN(right) ? right : `${right}px`; posLeft = "auto"; } else { posLeft = `${Math.max(clientVisibleWidth / 2 - boxElem.offsetWidth / 2)}px`; } } if (top && !topCenter) { posTop = isNaN(top) ? top : `${top}px`; } else { if (bottom && !bottomCenter) { posBottom = isNaN(bottom) ? bottom : `${bottom}px`; posTop = "auto"; } else { posTop = `${Math.max(clientVisibleHeight / 2 - boxElem.offsetHeight / 2)}px`; } } if (top === "topCenter") { posTop = "16px"; // posLeft = `${Math.max(clientVisibleWidth / 2 - boxElem.offsetWidth / 2)}px`; posLeft = "50%"; boxElem.style.marginLeft = `${-Math.max(boxElem.offsetWidth / 2)}px`; } if (top === "topLeft") { posTop = "16px"; posLeft = "16px"; } if (top === "topRight") { posTop = "16px"; posRight = "16px"; } if (bottom === "bottomCenter") { posBottom = "16px"; // posLeft = `${Math.max(clientVisibleWidth / 2 - boxElem.offsetWidth / 2)}px`; posLeft = "50%"; boxElem.style.marginLeft = `${-Math.max(boxElem.offsetWidth / 2)}px`; } if (bottom === "bottomLeft") { posBottom = "16px"; posLeft = "16px"; } if (bottom === "bottomRight") { posBottom = "16px"; posRight = "16px"; } if (top === "center" && _fixed === "absolute") { posTop = "50%"; posLeft = "50%"; boxElem.style.marginTop = `${-Math.max(boxElem.offsetHeight / 2)}px`; boxElem.style.marginLeft = `${-Math.max(boxElem.offsetWidth / 2)}px`; } if (posTop) boxElem.style.top = posTop; if (posLeft) boxElem.style.left = posLeft; if (posBottom) boxElem.style.bottom = posBottom; if (posRight) boxElem.style.right = posRight; }); }; // 重写Function.bind function bind(fn, obj) { let slice = Array.prototype.slice; if (fn.bind) { return fn.bind.apply(fn, slice.call(arguments, 1)); } let args = slice.call(arguments, 2); return function () { return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments); }; } /** * 根据点、像素半径,生成当前比例尺下,矩形的geojson。 * 使用场景:点击地图,生成缓冲矩形。 * @param mapZoom 当前地图级别 * @param resolutions 地图分辨率。如果map是默认3857,就传null * @param units 分辨率的单位。meter/degree * @param latlng leaflet的点对象。L.latlng * @param tolerance 容差。单位:像素 * @returns GeoJSON * @example * map.on("click", e => { * const mapZoom = that.map.getZoom(); * const res = that.webMapInfo && that.webMapInfo.resolutions ? that.webMapInfo.resolutions : null; * const units = that.webMapInfo ? that.webMapInfo.spatialReference.units : "meter"; * createRectByPoint(mapZoom, res, units, e.latlng, 5); * }); */ function createRectByPoint(mapZoom, resolutions, units, latlng, tolerance = 5) { if (!resolutions) { resolutions = [156543.03392799987, 78271.51696399994, 39135.75848199997, 19567.879240999984, 9783.939620499992, 4891.96981025013, 2445.984905125065, 1222.9924525623999, 611.4962262811999, 305.74811314059997, 152.87405657029998, 76.43702828514999, 38.218514142574996, 19.109257071287498, 9.554628535643749, 4.777314267954167, 2.3886571339770835, 1.19432856685625, 0.5971642835604166, 0.29858214164791663]; } let resol; const meters_per_degree = 111319.490793274; if (units !== "degree") { resol = resolutions[mapZoom] / meters_per_degree; } else { resol = resolutions[mapZoom]; } const a = resol * tolerance; let lng_min, lng_max, lat_min, lat_max; lat_min = latlng.lat - a; lat_max = latlng.lat + a; lng_min = latlng.lng - a; lng_max = latlng.lng + a; return { type: "Polygon", coordinates: [[[lng_min, lat_max], [lng_max, lat_max], [lng_max, lat_min], [lng_min, lat_min], [lng_min, lat_max]]] }; } }(); module.exports = __webpack_exports__; /******/ })() ;