SWT:gc.drawPolyline

//GC.drawPolyline(int[] pointArray);这条语句绘制了一系列互相连接的线段,作为参数的数组用于描述点的位置
 gc.drawPolyline(pointArray);//若要形成闭合的图形,第一个点和最后一个点坐标必须一致

<template> <view> <view class="map" id="mapDiv" style="width: 100%;height: 80vh;z-index: 0;position: relative;" :prop="dataOption" :change:prop="Trenderjs.initTMap" :change:renderTrigger="Trenderjs.handleMessage" :renderTrigger="triggerCounter"> </view> </view> </template> <script> export default { data() { return { msg: '我是service层原来的msg', triggerCounter: 0, isProcessing: false, message: null }; }, props: { dataOption: { type: String, default: '' }, }, methods: { renderjsData() { if (this.isProcessing) return; this.isProcessing = true; this.triggerCounter++; }, someMethodInVue(newVal) { this.$emit('childEvent', newVal); this.message = newVal; this.isProcessing = false; } } }; </script> <script module="Trenderjs" lang="renderjs"> var control; export default { data() { return { tk: '27657afc3318f8f2166fceba83427734', options: { lng: '104.397894', lat: '31.126855', }, iconType: "default", dataList: [], pointList: [], Tmap: null, gisDataObj: {}, gisData: {}, geocode: null, gisPointLngLat: {}, // 新增定位优化相关变量 positionBuffer: [], // 位置缓冲区 bufferSize: 5, // 缓冲区大小 lastPosition: null, // 上次位置 lastTimestamp: 0, // 上次时间戳 realTimeMarker: null, // 实时定位标记 realTimeLabel: null // 实时定位标签 } }, mounted() { if (!window.T) { const script = document.createElement('script') script.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk=' + this.tk document.head.appendChild(script) script.onload = this.initChartsRender.bind() } else { this.initMap(); } }, methods: { // 初始化地图 initMap() { const { lng, lat } = this.options; this.Tmap = new T.Map('mapDiv'); this.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); this.Tmap.setStyle("indigo"); this.Tmap.disableDoubleClickZoom(); this.Tmap.disableScrollWheelZoom(); this.Tmap.disableInertia(); this.Tmap.disableKeyboard(); this.geocode = new T.Geocoder(); control = new T.Control.Zoom(); this.Tmap.addControl(control); control.setPosition(T_ANCHOR_BOTTOM_RIGHT); }, // 若没有加载地图方法 initChartsRender() { this.initMap(); }, // 初始化地图数据 initTMap(newValue, oldValue) { let that = this; // 清除旧的定位监听 that._watchId && plus.geolocation.clearWatch(that._watchId); // 启动新的定位监听 that._watchId = plus.geolocation.watchPosition( position => that._handlePosition(position), err => console.log(err), { provider: 'system', enableHighAccuracy: true, maximumAge: 0, timeout: 10000 } ); // 处理传入的地图数据 if (newValue) { setTimeout(function() { try { that.gisDataObj = JSON.parse(newValue); that.gisData = JSON.parse(that.gisDataObj.data); let gisPoint = JSON.parse(that.gisData.data); that.gisPointLngLat = gisPoint; // 设置中心点 let centerLng, centerLat; if (that.gisData.type == 'marker') { centerLng = gisPoint.lng; centerLat = gisPoint.lat; } else if (that.gisData.type == 'polyline' || that.gisData.type == 'polygon') { centerLng = gisPoint[0].lng; centerLat = gisPoint[0].lat; } else { centerLng = '104.397894'; centerLat = '31.126855'; } that.Tmap.centerAndZoom(new T.LngLat(centerLng, centerLat), 15); // 绘制地图元素 that._drawMapElements(); } catch (e) { console.error('数据解析错误:', e); } }, 1000); } }, // 处理定位点 - 核心优化 _handlePosition(position) { const coords = position.coords; const now = Date.now(); const newPoint = { lng: coords.longitude, lat: coords.latitude, accuracy: coords.accuracy, timestamp: now }; console.log(`实时定位:${newPoint.lng.toFixed(6)},${newPoint.lat.toFixed(6)}`); // 应用移动平均滤波 const smoothedPoint = this._smoothPosition(newPoint); // 更新地图标记 this._updateRealTimeMarker(smoothedPoint); // 更新位置记录 this.lastPosition = smoothedPoint; this.lastTimestamp = now; }, // 移动平均滤波算法 _smoothPosition(newPoint) { // 添加到缓冲区 this.positionBuffer.push(newPoint); // 保持缓冲区大小 if (this.positionBuffer.length > this.bufferSize) { this.positionBuffer.shift(); } // 计算平均值 const sum = this.positionBuffer.reduce((acc, point) => { acc.lng += point.lng; acc.lat += point.lat; return acc; }, { lng: 0, lat: 0 }); return { lng: sum.lng / this.positionBuffer.length, lat: sum.lat / this.positionBuffer.length, accuracy: newPoint.accuracy }; }, // 更新实时定位标记 _updateRealTimeMarker(point) { const mapPoint = new T.LngLat(point.lng, point.lat); // 清除旧标记 if (this.realTimeMarker) this.Tmap.removeOverLay(this.realTimeMarker); if (this.realTimeLabel) this.Tmap.removeOverLay(this.realTimeLabel); // 创建新标记 this.realTimeMarker = new T.Marker(mapPoint); this.Tmap.addOverLay(this.realTimeMarker); // 创建文本标签 this.realTimeLabel = new T.Label({ text: `实时定位:${point.lng.toFixed(6)},${point.lat.toFixed(6)}`, position: mapPoint, offset: new T.Point(-40, 10) }); this.Tmap.addOverLay(this.realTimeLabel); // 平滑移动地图中心 this.Tmap.panTo(mapPoint); }, // 绘制地图元素 _drawMapElements() { if (!this.gisData || !this.gisPointLngLat) return; switch (this.gisData.type) { case 'marker': this._drawMarker(); break; case 'polyline': this._drawPolyline(); break; case 'polygon': this._drawPolygon(); break; } }, // 绘制标记点 _drawMarker() { const point = new T.LngLat(this.gisPointLngLat.lng, this.gisPointLngLat.lat); const marker = new T.Marker(point); this.Tmap.addOverLay(marker); const label = new T.Label({ text: this.gisData.name, position: point, offset: new T.Point(-40, 10) }); this.Tmap.addOverLay(label); }, // 绘制折线 _drawPolyline() { const points = this.gisPointLngLat.map(p => new T.LngLat(p.lng, p.lat) ); const polyline = new T.Polyline(points, { color: this.gisDataObj.color || '#FF0000', weight: 6 }); this.Tmap.addOverLay(polyline); // 添加终点标签 const endPoint = points[points.length - 1]; const label = new T.Label({ text: this.gisData.name, position: endPoint, offset: new T.Point(-40, 10) }); this.Tmap.addOverLay(label); }, // 绘制多边形 _drawPolygon() { const points = this.gisPointLngLat.map(p => new T.LngLat(p.lng, p.lat) ); const polygon = new T.Polygon(points, { color: this.gisDataObj.color || '#1E90FF', weight: 6 }); this.Tmap.addOverLay(polygon); // 添加中心点标签 const center = this._calculateCenter(points); const label = new T.Label({ text: this.gisData.name, position: center, offset: new T.Point(-40, 10) }); this.Tmap.addOverLay(label); }, // 计算多边形中心点 _calculateCenter(points) { const sum = points.reduce((acc, point) => { acc.lng += point.getLng(); acc.lat += point.getLat(); return acc; }, { lng: 0, lat: 0 }); return new T.LngLat( sum.lng / points.length, sum.lat / points.length ); }, // RenderJS事件处理器 handleMessage(newVal, oldVal) { if (newVal !== oldVal && this.gisPointLngLat) { const geolocation = new T.Geolocation(); geolocation.getCurrentPosition(e => { const distance = this.getDistance( e.lnglat.lat, e.lnglat.lng, this.gisPointLngLat.lat, this.gisPointLngLat.lng ); this.$ownerInstance.callMethod('someMethodInVue', { lng: e.lnglat.lng, lat: e.lnglat.lat, distance: distance * 1000 }); }); } }, // 计算两点间距离(Haversine公式) getDistance(lat1, lng1, lat2, lng2) { const radLat1 = (lat1 * Math.PI) / 180.0; const radLat2 = (lat2 * Math.PI) / 180.0; const a = radLat1 - radLat2; const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0; const s = 2 * Math.asin( Math.sqrt( Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2) ) ); return s * 6378.137; // 返回公里数 } } }; </script> 还是没有和搞个百度地图那样平稳的点运动轨迹
07-02
<template> <div style="width:100vw;height: 100vh;position: relative;"> <div id="cesiumContainer" style="width: 100%; height: 100%;"></div> <div class="control-panel"> <button @click="startDrawing" :disabled="isDrawing">绘制航线</button> <button @click="clearAll">清除所有</button> <button @click="flyAlongRoute" :disabled="routeEntities.length === 0">沿航线飞行</button> <button @click="showPointsCoordinates">显示点位坐标</button> <div v-if="isDrawing" class="drawing-hint">左键添加点,右键结束绘制</div> <div v-if="pointsCoordinates.length > 0" class="coordinates-display"> <h4>点位坐标:</h4> <div v-for="(point, index) in pointsCoordinates" :key="index"> 点{{ point.index }}: 经度 {{ point.longitude.toFixed(6) }}, 纬度 {{ point.latitude.toFixed(6) }}, 高度 {{ point.height.toFixed(2) }}米 </div> </div> </div> </div> </template> <script setup lang="ts"> import * as Cesium from 'cesium'; import { onMounted, ref } from 'vue'; const viewerRef = ref<Cesium.Viewer | null>(null); const activeShapePoints = ref<Cesium.Cartesian3[]>([]); const activeShape = ref<Cesium.Entity | null>(null); const floatingPoint = ref<Cesium.Entity | null>(null); const isDrawing = ref(false); const routeEntities = ref<Cesium.Entity[]>([]); const handlerRef = ref<Cesium.ScreenSpaceEventHandler | null>(null); const pointsCoordinates = ref<Array<{ index: number; longitude: number; latitude: number; height: number; }>>([]); onMounted(() => { //cesium的token Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNzRhOGU5OC1jMzI4LTQ3MWQtOTFkYy0xMTI3ZmFiYzJmM2IiLCJpZCI6MzIxNTEwLCJpYXQiOjE3NTI1NjIxOTR9.9SsH52T3GnTXrBaJ5lPQRnkmxphn4G0G644u34SzTwk"; //天地图的token const token = 'ffb871cd7ca48883db3b04cfd00d469f'; //天地图的url const tdtUrl = 'https://t{s}.tianditu.gov.cn/'; const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']; const viewer = new Cesium.Viewer('cesiumContainer', { animation: false, baseLayerPicker: false, fullscreenButton: false, vrButton: false, geocoder: false, homeButton: false, infoBox: false, sceneModePicker: false, selectionIndicator: false, timeline: false, navigationHelpButton: false, shouldAnimate: false, }); viewerRef.value = viewer; // 加载影像图层 viewer.imageryLayers.addImageryProvider( new Cesium.UrlTemplateImageryProvider({ url: tdtUrl + 'DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + token, subdomains: subdomains, tilingScheme: new Cesium.WebMercatorTilingScheme(), maximumLevel: 18 }) ); viewer.imageryLayers.addImageryProvider( new Cesium.UrlTemplateImageryProvider({ url: tdtUrl + 'DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=' + token, subdomains: subdomains, tilingScheme: new Cesium.WebMercatorTilingScheme(), maximumLevel: 18 }) ); // 飞行到指定经纬度 setTimeout(() => { viewer.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(104.625343, 28.525149, 1000), //经度、纬度、高度 duration: 1, //飞行时间 easingFunction: Cesium.EasingFunction.LINEAR_NONE, }); }, 500); // 启用深度检测 viewer.scene.globe.depthTestAgainstTerrain = true; }); // 绘制航线 const startDrawing = () => { const viewer = viewerRef.value; if (!viewer || isDrawing.value) return; // 清除之前的绘制状态 if (handlerRef.value) { handlerRef.value.destroy(); handlerRef.value = null; } // 重置状态 activeShapePoints.value = []; isDrawing.value = true; // 创建新的事件处理器 const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); handlerRef.value = handler; handler.setInputAction((movement: any) => { const earthPosition = viewer.scene.pickPosition(movement.position); if (!earthPosition) { console.warn("无法获取地面位置,请确保地形已加载"); return; } if (activeShapePoints.value.length === 0) { // 第一个点 floatingPoint.value = createPoint(earthPosition); activeShapePoints.value.push(earthPosition); activeShape.value = createDynamicShape(activeShapePoints.value); } else { // 后续点 activeShapePoints.value.push(earthPosition); createPoint(earthPosition); } }, Cesium.ScreenSpaceEventType.LEFT_CLICK); handler.setInputAction((movement: any) => { if (activeShapePoints.value.length === 0) return; const earthPosition = viewer.scene.pickPosition(movement.endPosition); if (!earthPosition || !floatingPoint.value) return; floatingPoint.value.position = earthPosition as never; if (activeShapePoints.value.length > 1) { activeShapePoints.value.pop(); } activeShapePoints.value.push(earthPosition); }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); handler.setInputAction(() => { if (activeShapePoints.value.length < 2) { console.warn("至少需要两个点来创建航线"); return; } terminateShape(); }, Cesium.ScreenSpaceEventType.RIGHT_CLICK); }; // 获取所有点位坐标 const getAllPointsCoordinates = () => { const viewer = viewerRef.value; if (!viewer || activeShapePoints.value.length === 0) return []; return activeShapePoints.value.map((point, index) => { const cartographic = Cesium.Cartographic.fromCartesian(point); return { index: index + 1, longitude: Cesium.Math.toDegrees(cartographic.longitude), latitude: Cesium.Math.toDegrees(cartographic.latitude), height: cartographic.height }; }); }; const showPointsCoordinates = () => { pointsCoordinates.value = getAllPointsCoordinates(); }; const createPoint = (position: Cesium.Cartesian3) => { const viewer = viewerRef.value; if (!viewer) return null; const point = viewer.entities.add({ position: position, point: { color: Cesium.Color.RED, pixelSize: 10, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, disableDepthTestDistance: Number.POSITIVE_INFINITY // 确保点始终可见 }, label: { text: `点 ${routeEntities.value.length}`, font: '14pt sans-serif', style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth: 2, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, pixelOffset: new Cesium.Cartesian2(0, -10), heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, disableDepthTestDistance: Number.POSITIVE_INFINITY } }); routeEntities.value.push(point); return point; }; const createDynamicShape = (positions: Cesium.Cartesian3[]) => { const viewer = viewerRef.value; if (!viewer) return null; const shape = viewer.entities.add({ polyline: { positions: new Cesium.CallbackProperty(() => positions, false), width: 3, material: Cesium.Color.YELLOW.withAlpha(0.7), clampToGround: true } }); routeEntities.value.push(shape); return shape; }; const terminateShape = () => { const viewer = viewerRef.value; if (!viewer || !activeShape.value) return; // 固定最终形状 activeShape.value.polyline!.positions = activeShapePoints.value as never; // 添加方向箭头 addDirectionArrows(activeShapePoints.value); // 清理临时状态 cleanupDrawing(); console.log("航线绘制完成,共", activeShapePoints.value.length, "个点"); }; const cleanupDrawing = () => { const viewer = viewerRef.value; if (!viewer) return; if (handlerRef.value) { handlerRef.value.destroy(); handlerRef.value = null; } if (floatingPoint.value) { viewer.entities.remove(floatingPoint.value); floatingPoint.value = null; } activeShape.value = null; // isDrawing.value = false; }; const addDirectionArrows = (positions: Cesium.Cartesian3[]) => { const viewer = viewerRef.value; if (!viewer || positions.length < 2) return; // 计算箭头间距 const step = Math.max(1, Math.floor(positions.length / 5)); for (let i = 0; i < positions.length - 1; i += step) { const start = positions[i]; const end = positions[i + 1]; const arrowEntity = viewer.entities.add({ position: end, billboard: { image: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSIjRkZGRjAwIiBkPSJNMTIgMkw0IDEyaDM1bC03IDcgNyA3SDQiLz48L3N2Zz4=', width: 32, height: 32, rotation: computeRotation(start, end), heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, disableDepthTestDistance: Number.POSITIVE_INFINITY } }); routeEntities.value.push(arrowEntity); } }; const computeRotation = (start: Cesium.Cartesian3, end: Cesium.Cartesian3) => { const cartographicStart = Cesium.Cartographic.fromCartesian(start); const cartographicEnd = Cesium.Cartographic.fromCartesian(end); const lon1 = Cesium.Math.toDegrees(cartographicStart.longitude); const lat1 = Cesium.Math.toDegrees(cartographicStart.latitude); const lon2 = Cesium.Math.toDegrees(cartographicEnd.longitude); const lat2 = Cesium.Math.toDegrees(cartographicEnd.latitude); const dLon = (lon2 - lon1) * Math.PI / 180.0; const y = Math.sin(dLon) * Math.cos(lat2 * Math.PI / 180.0); const x = Math.cos(lat1 * Math.PI / 180.0) * Math.sin(lat2 * Math.PI / 180.0) - Math.sin(lat1 * Math.PI / 180.0) * Math.cos(lat2 * Math.PI / 180.0) * Math.cos(dLon); return Math.atan2(y, x); }; const clearAll = () => { const viewer = viewerRef.value; if (!viewer) return; cleanupDrawing(); routeEntities.value.forEach(entity => { try { viewer.entities.remove(entity); } catch (e) { console.warn("移除实体时出错:", e); } }); isDrawing.value = false; routeEntities.value = []; activeShapePoints.value = []; }; const flyAlongRoute = () => { const viewer = viewerRef.value; if (!viewer || activeShapePoints.value.length < 2) return; const property = new Cesium.SampledPositionProperty(); // 设置时间轴 const startTime = Cesium.JulianDate.fromDate(new Date()); const stopTime = Cesium.JulianDate.addSeconds( startTime, activeShapePoints.value.length * 2, new Cesium.JulianDate() ); viewer.clock.startTime = startTime.clone(); viewer.clock.stopTime = stopTime.clone(); viewer.clock.currentTime = startTime.clone(); viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; viewer.clock.multiplier = 1; // 安全调用 timeline if (viewer.timeline) { viewer.timeline.zoomTo(startTime, stopTime); } else { console.warn("Timeline 不可用,请确保 Viewer 初始化时启用了 timeline"); } // 添加位置样本 activeShapePoints.value.forEach((point, index) => { const time = Cesium.JulianDate.addSeconds( startTime, index * 2, new Cesium.JulianDate() ); property.addSample(time, point); }); // 创建相机实体 const cameraEntity = viewer.entities.add({ position: property, orientation: new Cesium.VelocityOrientationProperty(property), model: { uri: 'https://assets.agi.com/models/aircraft/CesiumAir/Cesium_Air.glb', minimumPixelSize: 64, maximumScale: 20000 }, path: { resolution: 1, material: new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.1, color: Cesium.Color.YELLOW }), width: 10 } }); // 跟踪相机实体 viewer.trackedEntity = cameraEntity; routeEntities.value.push(cameraEntity); // 开始动画 viewer.clock.shouldAnimate = true; }; </script> <style scoped> .control-panel { position: absolute; top: 10px; left: 10px; z-index: 999; background: rgba(42, 42, 42, 0.8); padding: 10px; border-radius: 5px; color: white; } .control-panel button { display: block; margin: 5px 0; padding: 8px 12px; background: #4a4a4a; color: white; border: none; border-radius: 3px; cursor: pointer; min-width: 100px; } .control-panel button:hover { background: #5a5a5a; } .control-panel button:disabled { background: #3a3a3a; color: #777; cursor: not-allowed; } .drawing-hint { margin-top: 10px; font-size: 12px; color: #ccc; } .coordinates-display { margin-top: 10px; max-height: 200px; overflow-y: auto; font-size: 12px; background: rgba(0, 0, 0, 0.5); padding: 5px; border-radius: 3px; } .coordinates-display div { margin: 3px 0; padding: 2px; } </style> 帮我封装ts部分,不要使用类,使用函数形式,支持响应式,可以多个地方使用
07-16
<template> <view> <view class="map" id="mapDiv" style="width: 100%;height: 80vh;z-index: 0;position: relative;" :prop="dataOption" :change:prop="Trenderjs.initTMap" :change:renderTrigger="Trenderjs.handleMessage" :renderTrigger="triggerCounter"> </view> </view> </template> <script> export default { data() { return { msg: '我是service层原来的msg', triggerCounter: 0, isProcessing: false, // 新增状态锁 message: null }; }, props: { dataOption: { type: String, default: '' }, }, methods: { renderjsData() { console.log('----------', this.triggerCounter); if (this.isProcessing) return; // 阻止重复触发 this.isProcessing = true; this.triggerCounter++ console.log('=============', this.triggerCounter); }, someMethodInVue(newVal) { console.log('位置', newVal); this.$emit('childEvent', newVal); this.message = newVal this.isProcessing = false; } } }; </script> <script module="Trenderjs" lang="renderjs"> var control; export default { data() { return { tk: '27657afc3318f8f2166fceba83427734', options: { lng: '104.397894', lat: '31.126855', }, iconType: "default", dataList: [], pointList: [], Tmap: null, gisDataObj: {}, gisData: {}, geocode: null, gisPointLngLat: {} } }, mounted() { if (!window.T) { console.log('00000', ); const script = document.createElement('script') script.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk=' + this.tk // this.initChartsRender.bind() document.head.appendChild(script) script.onload = this.initChartsRender.bind() } else { console.log('++++', ); const { lng, lat } = this.options this.Tmap = null; console.log(this.Tmap); this.Tmap = new T.Map('mapDiv'); this.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); this.Tmap.setStyle("indigo"); //设置地图主体颜色indigo this.Tmap.disableDoubleClickZoom(); this.Tmap.disableScrollWheelZoom(); this.Tmap.disableInertia() this.Tmap.disableKeyboard() //创建对象 this.geocode = new T.Geocoder(); control = new T.Control.Zoom(); this.Tmap.addControl(control); var controlPosition = T_ANCHOR_BOTTOM_RIGHT; control.setPosition(controlPosition); // Tmap.enableDrag(); // this.setIcon(lng, lat, true, '') } }, created() { }, methods: { // 初始化地图 initTMap(newValue, oldValue) { let that = this; // 开启实时定位监听 that._watchId && plus.geolocation.clearWatch(that._watchId); // 先清除旧的监听 that._watchId = plus.geolocation.watchPosition(successCB => { let data = { lng: successCB.coords.longitude, lat: successCB.coords.latitude } console.log('实时定位:', data.lng, data.lat); that.Tmap.centerAndZoom(new T.LngLat(data.lng, data.lat), 20); var point = new T.LngLat(data.lng, data.lat); const marker = new T.Marker(point, { // icon }); that.Tmap.clearOverLays(); // 可选:每次清除旧的覆盖物 that.Tmap.addOverLay(marker); var label = new T.Label({ text: '实时定位:' + data.lng + ',' + data.lat, position: point, offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); }, err => { console.log(err); }, { provider: 'system', enableHighAccuracy: true, }); // let that = this if (newValue) { setTimeout(function() { console.log(JSON.parse(newValue)); that.gisDataObj = JSON.parse(newValue) console.log(JSON.parse(that.gisDataObj.data)); that.gisData = JSON.parse(that.gisDataObj.data) // if (that.gisData.length > 0) { // that.options = { // lng: that.pointList[0].deviceDeploymentLocation.split(',')[1], // lat: that.pointList[0].deviceDeploymentLocation.split(',')[0] // } // } else { let gisPoint = JSON.parse(that.gisData.data) that.gisPointLngLat = JSON.parse(that.gisData.data) if (that.gisData.type == 'marker') { that.options = { lng: gisPoint.lng, lat: gisPoint.lat, } } else if (that.gisData.type == 'polyline' || that.gisData.type == 'polygon') { that.options = { lng: gisPoint[0].lng, lat: gisPoint[0].lat, } } else { that.options = { lng: '104.397894', lat: '31.126855', } } const { lng, lat } = that.options that.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); if (that.gisData.type == 'marker') { var point = new T.LngLat(gisPoint.lng, gisPoint.lat); console.log(point); const marker = new T.Marker(point, { // icon }); that.Tmap.addOverLay(marker); var label = new T.Label({ text: that.gisData.name, position: point, offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } else if (that.gisData.type == 'polyline') { let points = []; for (let i = 0; i < gisPoint.length; i++) { points.push(new T.LngLat(gisPoint[i].lng, gisPoint[i].lat)); } //创建线对象 var line = new T.Polyline(points, { color: that.gisDataObj.color, weight: 6, }); //向地图上添加线 that.Tmap.addOverLay(line); var label = new T.Label({ text: that.gisData.name, position: points[points.length - 1], offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } else if (that.gisData.type == 'polygon') { let points = []; for (let i = 0; i < gisPoint.length; i++) { points.push(new T.LngLat(gisPoint[i].lng, gisPoint[i].lat)); } //创建线对象 var polygon = new T.Polygon(points, { color: that.gisDataObj.color, weight: 6, }); //向地图上添加线 that.Tmap.addOverLay(polygon); var label = new T.Label({ text: that.gisData.name, position: points[points.length - 1], offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } }, 1000); } }, // 若没有加载地图方法 initChartsRender() { const { lng, lat } = this.options var that = this; this.Tmap = new T.Map('mapDiv'); this.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); this.Tmap.setStyle("indigo"); //设置地图主体颜色indigo this.Tmap.disableDoubleClickZoom(); this.Tmap.disableScrollWheelZoom(); this.Tmap.disableInertia() this.Tmap.disableKeyboard() control = new T.Control.Zoom(); this.Tmap.addControl(control); var controlPosition = T_ANCHOR_BOTTOM_RIGHT; control.setPosition(controlPosition); // Tmap.enableDrag(); // this.setIcon(lng, lat, true, '') }, // 地图图标Icon setIcon(lng, lat, isClear, markerActive) { if (isClear) { // if (this.iconType == 'searchIcon') { // this.Tmap.clearOverLays() // } else { this.Tmap.removeOverLay(markerActive) // } } console.log(this.gisData); let gisPoint = JSON.parse(this.gisData.data) }, // RenderJS事件处理器 handleMessage(newVal, oldVal) { console.log(newVal, oldVal); if (newVal !== oldVal) { const center = this.Tmap.getCenter(); var lo = new T.Geolocation(); let that = this // let gisPoint = JSON.parse(this.gisData.data) const fn = function(e) { let distance = that.getDistance(e.lnglat.lat, e.lnglat.lng, that.gisPointLngLat.lat, that .gisPointLngLat.lng) that.$ownerInstance.callMethod('someMethodInVue', { lng: e.lnglat.lng, lat: e.lnglat.lat, distance: distance * 1000 }); // // if (this.getStatus() == 0) { // that.Tmap.centerAndZoom(e.lnglat, 15) // console.log('e.lnglat000', e.lnglat.lat, e.lnglat.lng); // // var marker = new T.Marker(e.lnglat); // // that.Tmap.addOverLay(marker); // // } // // if (this.getStatus() == 1) { // console.log('e.lnglat111', e.lnglat.lat, e.lnglat.lng); // that.Tmap.centerAndZoom(e.lnglat, e.level) // // var marker = new T.Marker(e.lnglat); // // that.Tmap.addOverLay(marker); // // } } lo.getCurrentPosition(fn); } }, getDistance(lat1, lng1, lat2, lng2) { console.log(lat1, lng1, lat2, lng2); const radLat1 = (lat1 * Math.PI) / 180.0 const radLat2 = (lat2 * Math.PI) / 180.0 const a = radLat1 - radLat2 const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0 let s = 2 * Math.asin( Math.sqrt( Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2) ) ) s *= 6378.137 // EARTH_RADIUS; s = Math.round(s * 100) / 100 console.log(s); return s // 调用 return的距离单位为km } }, } </script> 只在这段代码的基础上修复漂移的问题即可
07-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值