/** * [ONEMAP.M.projectController] * @return {[object]} */ define([ 'html!templates/menu/vectorInfo', 'css!styles/menu/vectorInfo', ], function (dialogLayout) { /** * 初始化并订阅事件 * @return {[type]} [description] */ /** * 模块数据 用于数据存储和外部调用 * @type {Object} * 数据存放 */ var modValue = { VECTOR: {}, handler: null, nowOpenDialogLayerId: null, } function add(item, cancelSelected) { modValue.cancelSelected = cancelSelected // if (ONEMAP.M.myLayers.checkLength() >= map23DConfig.layerMaxLength) { // ONEMAP.C.publisher.publish({ type: 'warning', message: '图层数量已达上限' }, 'noteBar::add'); // modValue.cancelSelected(item.id) // return; // } var modelData = { "category": "倾斜摄影", "info": "", "name": item.title, "layerInfo": item } var options = {}; let request1 = fetch(onemapUrlConfig.DMS_URL + '/dms/content/selectContentList', { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "token": localStorage.getItem("systemToken"), }, mode: "cors", body: "columnId=" + modelData.layerInfo.id }).then(resp => resp.json()) let request2 = fetch(onemapUrlConfig.DMS_URL + '/dms/content/getVectorData', { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "token": localStorage.getItem("systemToken"), }, mode: "cors", body: "columnId=" + modelData.layerInfo.id + "&token=" + localStorage.getItem("systemToken") // body: "columnId=" + modelData.layerInfo.id }).then(resp => resp.json()) // 创建一个Promise数组 const promises = [request1, request2] // 使用Promise.all来等待所有请求完成 Promise.all(promises).then(responses => { // 所有请求都成功完成时,这里的代码会被执行 // `responses`是一个数组,包含了所有请求的响应结果 // console.log(responses); let styleRes = responses[0] let geojsonRes = responses[1] if (styleRes.code != 200) { ONEMAP.C.publisher.publish({ type: 'warning', message: styleRes.message, }, 'noteBar::add'); return } if (geojsonRes.code != undefined) { ONEMAP.C.publisher.publish({ type: 'warning', message: geojsonRes.message, }, 'noteBar::add'); return } if (geojsonRes.features.length == 0) { ONEMAP.C.publisher.publish({ type: 'warning', message: "当前图层无数据!", }, 'noteBar::add'); return } let style = JSON.parse(styleRes.content.data[0].c_style).style modelData.geo = geojsonRes let promise = add3DVECTOR(modelData, style); promise.then(function (guid) { options = { action: "add", DOM: { guid: guid, type: "VECTOR", name: item.title, }, mod: "VECTOR" } if (!guid) return ONEMAP.M.myLayers.myLayerControl(options); // 添加信息到“我的图层” ONEMAP.C.publisher.subscribe(layerAction, guid); openClick(); }) }).catch(error => { // 如果任何一个请求失败,这里的代码会被执行 // console.error(error); ONEMAP.C.publisher.publish({ type: 'warning', message: error, }, 'noteBar::add'); }); } function remove(options) { var guid = options.guid ? options.guid : "VECTOR--" + options.id; removeVECTOR({ guid: guid }) ONEMAP.M.myLayers.myLayerControl({ action: "remove", DOMid: guid }); // 移除数据层 if (guid == modValue.nowOpenDialogLayerId) { closeEntityPropertiesDialog(); modValue.nowOpenDialogLayerId = null; } } function layerAction(options) { if (options.guid.split("--")[0] == "VECTOR") { if (options.action == "remove") { // removeVECTOR(options.guid) remove(options) modValue.cancelSelected(Number(options.guid.split("--")[1])); } else if (options.action == "opacity") { opacityVECTOR(options) } else if (options.action == "controlShow") { controlShowVECTOR(options) } else if (options.action == "up" || options.action == "down") { } else if (options.action == "location") { locationVECTOR(options) } } } // 获取 svg 的元素源码 function getAndSetSVGElement(svgUrl, color, token) { var oReq = new XMLHttpRequest(); oReq.open("GET", svgUrl, false); oReq.setRequestHeader("Content-type", "application/json"); // oReq.setRequestHeader("token", token); oReq.send(JSON.stringify()); let parser = new DOMParser(); let xmlDom = parser.parseFromString(oReq.responseText, "text/html"); xmlDom.querySelector("g>path").setAttribute("fill", color); return new XMLSerializer().serializeToString(xmlDom.querySelector("svg")); } function svgToImg(svgStr) { const blob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' }); // 创建一个 FileReader 对象来读取 Blob const reader = new FileReader(); reader.readAsDataURL(blob); // 当 FileReader 完成读取时,它会触发 'load' 事件 return new Promise((resolve) => { reader.onloadend = function () { resolve(reader.result) }; }) } // function reEncode(data) { // return decodeURIComponent( // encodeURIComponent(data).replace(/%([0-9A-F]{2})/g, (match, p1) => { // const c = String.fromCharCode(`0x${p1}`); // return c === '%' ? '%25' : c; // }) // ) // } function export2Base64Img(path, MIMEType, option) { // var serializer = new XMLSerializer(); // var source = serializer.serializeToString(svgDom); // 方式一: unescape(encodeURIComponent(txt)) // var path = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(source))); // 方式二: decodeURIComponent(encodeURIComponent(txt)) // var path = "data:image/svg+xml;base64," + window.btoa(reEncode(source)); var canvas = document.createElement("canvas"), context = canvas.getContext("2d"), img = new Image(), pixelRatio = window.devicePixelRatio || 1, _exportPath, handler option = option || {}; // canvas.width = parseFloat(svgDom.getAttribute('width')); // * pixelRatio // canvas.height = parseFloat(svgDom.getAttribute('height')); // * pixelRatio canvas.width = 500; canvas.height = 500; img.src = path; img.onload = function () { // 增加底色 if (option.background) { context.beginPath(); context.rect(0, 0, canvas.width, canvas.height); context.fillStyle = option.background; // context.fillStyle = "transparent"; context.fill(); context.closePath(); } // context.drawImage(img, 0, 0); var marker = option.watermark || ""; if (marker) { context.font = "18px 微软雅黑"; context.fillStyle = "rgba(12, 0, 70, 0.5)"; var textWidth = context.measureText(marker).width, textHegith = 50, pk = 1.2, rotate = (option.rotation || -45) * Math.PI / 180, sinReg = Math.sin(rotate), cosReg = Math.cos(rotate), width = Math.abs(canvas.width * cosReg) + Math.abs(canvas.height * sinReg), height = Math.abs(canvas.height * cosReg) + Math.abs(canvas.width * sinReg); var xf = Math.ceil(width / textWidth * pk); var yf = Math.ceil(height / textHegith); context.rotate(rotate); for (var i = 0; i < yf; i++) { for (var k = 0; k < xf; k++) { context.fillText(marker, textWidth * k * pk - canvas.height * cosReg, textHegith * i) } } } document.body.appendChild(canvas); _exportPath = canvas.toDataURL(MIMEType || 'image/png', 1) typeof handler === 'function' && handler(_exportPath) document.body.removeChild(canvas) } return new Promise(function (resolve, reject) { handler = resolve }) } /** * 加载 * @return {[type]} [description] */ async function add3DVECTOR(options, style) { // var guid = map23DControl.buildGuid('VECTOR-3DData'); var guid = "VECTOR--" + options.layerInfo.id let img = null; if (style.point) { // 获取svg let svg = getAndSetSVGElement(style.point.photo, style.point.color) // console.log(svg) img = await svgToImg(svg); // img = await export2Base64Img(img, "", { // background: "#ffffff00" // }); } Cesium.GeoJsonDataSource.load(options.geo).then( function (dataSource) { dataSource.name = guid; map3DViewer.map.dataSources.add(dataSource); modValue.VECTOR[guid] = dataSource; var entities = dataSource.entities.values; for (var i = 0; i < entities.length; i++) { var entity = entities[i]; if (entity.billboard) { entity.billboard = undefined; // entity.point = new Cesium.PointGraphics({ // show: true, // pixelSize: 15, // color: Cesium.Color.fromCssColorString("#aed0ff"), // outlineColor: Cesium.Color.fromCssColorString("#3388ff"), // outlineWidth: 2, // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // scaleByDistance: new Cesium.NearFarScalar(10000, 1, 20000, 0.5), // // translucencyByDistance: new Cesium.NearFarScalar(1500, 1, 20000, 0.2), // // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 20000) // }) entity.billboard = new Cesium.BillboardGraphics({ image: img, width: 50, height: 50, pixelOffset: new Cesium.Cartesian2(0, -25), heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // scaleByDistance: new Cesium.NearFarScalar(10000, 1, 20000, 0.75), }) } if (entity.polyline) { entity.polyline.width = style.polyline.width; entity.polyline.material = Cesium.Color.fromCssColorString(style.polyline.color).withAlpha(style.polyline.alpha); // 颜色 } if (entity.polygon) { entity.polygon.height = 0.2; entity.polygon.outline = true; // 边框是否显示 entity.polygon.outlineColor = Cesium.Color.fromCssColorString(style.polygon.outerColor); // 边框颜色 entity.polygon.outlineWidth = style.polygon.outerWidth; // 边框宽度 entity.polygon.material = Cesium.Color.fromCssColorString(style.polygon.innerColor).withAlpha(style.polygon.alpha);// 填充色 } entity.layerId = guid entity.mod = "vectorMod" } var extentR = turf.bbox(options.geo); map3DViewer.map.camera.flyTo({ destination: Cesium.Rectangle.fromDegrees(extentR[0] - 0.04, extentR[1] - 0.04, extentR[2] + 0.04, extentR[3] + 0.04), }); modValue.VECTOR[guid + "_extent"] = extentR; } ); return guid; }; function removeVECTOR(options) { map3DViewer.map.dataSources.remove(map3DViewer.map.dataSources.getByName(options.guid)[0]); delete modValue.VECTOR[options.guid]; delete modValue.VECTOR[options.guid + "_extent"]; if (Object.getOwnPropertyNames(modValue.VECTOR).length == 0) { closeClick(); } } function opacityVECTOR(options) { modValue.VECTOR[options.guid].entities.values.map(function (entity) { if (entity.point) { entity.point = new Cesium.PointGraphics({ show: true, pixelSize: 15, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, color: Cesium.Color.fromCssColorString("#aed0ff").withAlpha(options.options.opacity), outlineColor: Cesium.Color.fromCssColorString("#3388ff").withAlpha(options.options.opacity), outlineWidth: 2, scaleByDistance: new Cesium.NearFarScalar(10000, 1, 20000, 0.5), }) } if (entity.polyline) { entity.polyline.material = Cesium.Color.fromCssColorString("#3388ff").withAlpha(options.options.opacity); // 颜色 } if (entity.polygon) { entity.polygon.outlineColor = Cesium.Color.fromCssColorString("#3388ff").withAlpha(options.options.opacity); // 边框颜色 entity.polygon.material = Cesium.Color.fromCssColorString("#aed0ff").withAlpha(options.options.opacity);// 填充色 } }) } function controlShowVECTOR(options) { if (options.options.show) modValue.VECTOR[options.guid].show = true if (!options.options.show) modValue.VECTOR[options.guid].show = false } function locationVECTOR(options) { let extentR = modValue.VECTOR[options.guid + "_extent"] map3DViewer.map.camera.flyTo({ destination: Cesium.Rectangle.fromDegrees(extentR[0], extentR[1], extentR[2], extentR[3]), }); } function openClick() { if (modValue.handler) return; // 绑定点击事件 modValue.handler = new Cesium.ScreenSpaceEventHandler(map3DViewer.map.canvas); modValue.handler.setInputAction(function (movement) { if (ONEMAP.M.toolsBar.status.toolsShow) return; var pick = map3DViewer.map.scene.pick(movement.position); // 拾取鼠标所在的entity if (Cesium.defined(pick)) { let entity = pick.id; if (entity.mod && entity.mod == "vectorMod") { let properties = entity.properties.getValue(); openEntityPropertiesDialog(properties, entity.layerId); } } }, Cesium.ScreenSpaceEventType.LEFT_CLICK) } function closeClick() { if (modValue.handler) { modValue.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) modValue.handler = null; } } function openEntityPropertiesDialog(properties, layerId) { if ($("#vectorInfoModal").length != 1) { $('body').append(dialogLayout); //拖拽 $("#vectorInfoModal .popup-ct").dragmove($('#vectorInfoModal')); } else { $("#vectorInfoForm table").empty(); } $("#vectorInfoModal .title").text(properties.Name) let html = `

字段

值` $("#vectorInfoForm table").append(html) Object.getOwnPropertyNames(properties).map(function (field) { let html = `

${field}

${properties[field]}` $("#vectorInfoForm table").append(html) }) modValue.nowOpenDialogLayerId = layerId $("#vectorInfoModal .close").bind('click', function () { closeEntityPropertiesDialog(); }); } function closeEntityPropertiesDialog() { $("#vectorInfoModal").remove() } return ONEMAP.M.threeData = { add: add, remove: remove, } });