Vue3 使用天地图绘制车辆历史轨迹
Vue3中使用天地图,自定义出车辆历史轨迹如下

1. 引入
在index.html 中引入天地图在线链接
<!DOCTYPE html>
<html lang="">
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1.0"><link rel="icon" href="<%= BASE_URL %>favicon.ico"><title>德清餐厨垃圾收运处置监管平台</title>//引入天地图在线链接 tk 为你自己申请的tk<script src="https://api.tianditu.gov.cn/api?v=3.0&tk=你申请的tk"type="text/javascript"></script><script src="http://lbs.tianditu.gov.cn/js/lib/jquery/jquery-1.7.2.min.js"></script><!-- ECharts --><script src="https://cdn.jsdelivr.net/npm/echarts@5.0.2/dist/echarts.min.js"></script>
</head><body><noscript><strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.Please enable it to continue.</strong></noscript><div id="app"></div>
</body>
</html>
2. 使用
<template><div><!-- 车辆监督 --><div id="map" :style="{ height: mapHeight }"><div id="mapDiv" ref="mapDiv"></div><div style="display: none" id="guijimap" ref="guijimap"></div></div><!--车辆轨迹框部分--><div v-if="carTrack" class="tabbable-line guijitabbox carguiJiTabBox"><div class="tab-content"><div class="tab-pane active in" id="tab2_1" style="text-align: center"><p style="font-size: 16px; color: #000"><span id="carguijititle">{{ name }}</span></p><form role="form" class="form-horizontal"><div class="form-body"><div class="form-group"><label class="col-sm-3 control-label" for="form_control_1">日期</label><div class="col-sm-7"><a-date-pickerlocale='locale'@change="dateTimeChange(1, $event)"v-model:value="timeDate.date"format="YYYY-MM-DD":disabled-date="disabledDate"style="width: 100%"placeholder="选择日期"/></div></div><div class="form-group"><label class="col-sm-3 control-label" for="form_control_1">时刻</label><div class="col-sm-7"><div class="input-group fl"><a-time-pickerv-model:open="open1"style="width: 92px"v-model:value="timeDate.startTime"valueFormat="HH:mm:ss"placeholder=""><template #addon><a-buttonsize="small"type="primary"@click="dateTimeChange(2, $event)">确定</a-button></template></a-time-picker></div><span class="fl" style="margin-top: 5px"> ~ </span><div class="input-group fl"><a-time-pickerv-model:open="open2"style="width: 92px"v-model:value="timeDate.endTime"valueFormat="HH:mm:ss"placeholder=""><template #addon><a-buttonsize="small"type="primary"@click="dateTimeChange(3, $event)">确定</a-button></template></a-time-picker></div></div></div><div class="form-group"><!-- 轨迹播放快慢 --><label class="col-sm-3 control-label" for="form_control_1">轨迹播放</label><div class="col-sm-9" style="padding-left: 0; margin-top: 8px"><!-- <span class="fl"> 慢</span> --><span><a-slider:min="1"@change="sliderChange"style="width: 74%"id="test"v-model:value="timeDate.rangeValue"/></span><!-- <span class="fl"> 快</span> --></div></div></div></form><a-buttonv-if="startgj"@click="startTrack"style="padding: 0 5px; margin-right: 10px; color: '#5f5f5f'"><template #icon><CaretRightOutlined /></template>开始</a-button><a-buttonv-else@click="pauseTrack"style="padding: 0 5px; margin-right: 10px; color: '#5f5f5f'"><template #icon><CaretRightOutlined /></template>暂停</a-button><a-button@click="stopTrack"style="padding: 0 5px; margin-right: 10px"><template #icon><CloseSquareFilled /> </template>结束</a-button><a-button style="padding: 0 5px" @click="carTrackReturn"><template #icon><RollbackOutlined /></template>返回</a-button><div ref="time_box" style="width: 100%; margin-top: 10px"><divid="carguijiscroller"class="scroller tabselbox"data-rail-visible="1"data-rail-color="#ececec"data-handle-color="#bcbcbc"style="width: 100%; height: 350px; overflow: auto"><pv-for="(item, i) in timeList":key="i"class="showcarpoint gjtimelist"@click="clickCar(item, i)"><i class="guijinumlist">{{ i }}</i><span>{{ item.time }}</span></p></div></div></div></div></div></div>
</template>
<script>import {ref,reactive,toRefs,defineComponent,onMounted,getCurrentInstance,
} from "vue";
import {CarOutlined,DownOutlined,CaretRightOutlined,CloseSquareFilled,RollbackOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment, { Moment } from "moment";
import 'moment/dist/locale/zh-cn';import { format, } from "@/utils/util";
import { getcars_page, getcartrajectory_by_cid_time } from "@/api/system/api";
export default defineComponent({components: {CarOutlined,DownOutlined,CaretRightOutlined,CloseSquareFilled,RollbackOutlined,},setup() {// 在ts中直接使用 const { ctx }=getCurrentInstance().可能会报 Property 'ctx' does not exist on type 'ComponentInternalInstance | null'. 的错误.let { ctx } = getCurrentInstance();let state = reactive({count: 0,map: "",guijimap: "",zoom: 12,T: "",mapHeight: 800 + "px",timeDate: {date: undefined,startTime: "00:00:00",endTime: "23:59:59",rangeValue: 1,},carTrack: false,loading: false,obj_CarTrack: "",tile: "",timeList: [],timename: {},pagenum: 1,pagesize: 500,total: 10,carList: [],car_icon: "",detailAddress: "",v: {},icont: "",customerWinInfo: {},name: "",startgj: true,setCarTnterTime: 1000,linebottom: [],iguiji: 0,closetimeinter: 0,markercaruserlinelabel: null,markercarline: null,startGTime: "",onlinemarkercar: [],markerclick: {},});const open1 = ref(false);const open2 = ref(false);let getData = async (pagenum, pagesize) => {await getcars_page({ pagenum, pagesize }).then((res) => {state.carList = res.data.content;state.map.clearOverLays();clearMarkers();addMarker();});};state.timeDate.date = moment().format("YYYY-MM-DD");onMounted(() => {clearInterval(state.timename);getData(state.pagenum, state.pagesize);initMapHeight();initMap(state, ctx);window.onresize = () => {return (() => {if (window.innerWidth > 1664) {state.mapHeight = window.innerHeight - 150 + "px";} else {state.mapHeight = window.innerHeight - 118 + "px";}})();};state.cgjicon = new TIcon(require("../../assets/image/map/star.png"),new TSize(30, 30),{ anchor: new TPixel(15, 30) });});/*** @Author: zhai penghui* @Date: 2021-03-05 15:55:21* @函数名称: initMap* @函数功能: 初始化天地图* @函数参数:* @函数返回:* @param {*} state*/let initMap = () => {//初始化地图对象state.map = new TMap("mapDiv");//设置显示地图的中心点和级别state.map.centerAndZoom(new TLngLat(119.98107, 30.54072), 12);//允许鼠标双击放大地图state.map.enableHandleMouseScroll();};function initMapHeight() {let main = document.getElementById("map");main.style.height = window.innerHeight + "px";}function clearMarkers(params) {}function addMarker() {var lngLat,lngLatarr = [];var f = 0;state.carList.forEach((v, i) => {if (v.isonline == 1) {lngLat = new TLngLat(v.longitude, v.latitude);lngLatarr[i] = lngLat;//创建标注对象var icont = new TIcon(require("../../assets/image/map/caricon_10.png"),new TSize(28, 38),{anchor: new TPixel(12, 30),});state.icont = icont;state.onlinemarkercar[f] = new TMarker(lngLat, {icon: icont,});//向上地图上添加标注state.map.addOverLay(state.onlinemarkercar[f]);//注册标注的点击事件TEvent.addListener(state.onlinemarkercar[f], "click", function() {showonecarinfo(v, this);state.map.clearOverLays();addMarker();// state.map.removeOverLay(state.customerWinInfo);});f++;}});}// 点击具体车辆信息function showonecarinfo(v, callBackObject) {console.log(v, callBackObject);// state.map.removeOverLay(state.customerWinInfo);// 关闭查寻窗口var object = callBackObject;// DeleteInfoBox();let markerone;let geocode = new TGeocoder();geocode.getLocation(new TLngLat(v.longitude, v.latitude), searchResult);var lng = parseFloat(object.getLngLat().getLng());var lat = parseFloat(object.getLngLat().getLat());markerone = new TMarker(object.getLngLat(), {icon: state.icont,});state.map.addOverLay(markerone);markerone.setZindex(600);state.map.panTo(new TLngLat(lng, lat));function searchResult(result) {if (result.getStatus() == 0) {var html = "";html +="";html +="" +"车辆详情" +" +"ref=close" +" id='close' class='fa fa-times fr'>X ";html +="车 号 " +v.carcode +"
+ ''+" style='max-width:100px;max-height:110px;'/> ";// html += "驾驶员 " + "德清餐厨" + " ";// html += "联系方式 " + "13137657727" + " ";html += "车辆类型 " + v.carclasses + " ";html +="所属单位 " +v.manageunit +" GPS状态 " +"在线" +" ";html += " ";// html += "上报时间 " + "2021-02-03 09:33:10" + " ";html +="当前位置 " +result.getAddress() +" ";html +="车载视频: 车载视频1 车载视频2 车载视频3 ";html +=">>查看轨迹
";customerWinfun(object, html, v);}}}//******************************************************************************基本信息窗口function customerWinfun(e, html, v) {let customerWinInfo;var config1 = {offset: new TPixel(0, 0),position: e.getLngLat(),};customerWinInfo = new TLabel(config1);customerWinInfo.setTitle("");customerWinInfo.setLabel(html);customerWinInfo.getObject().style.zIndex = 10000;state.map.addOverLay(customerWinInfo);var obj = customerWinInfo.getObject();var width = parseInt(obj.offsetWidth);var height = parseInt(obj.offsetHeight);var icon = e.getIcon();var anchor_icon = icon.getAnchor();var pixel = new TPixel(width / -2, height / -2 - anchor_icon[1] - 20);customerWinInfo.setOffset(pixel);customerWinInfo.setZindex(600);$(".infowindiv").parent().css({padding: 0,border: "1px solid #999",});state.customerWinInfo = customerWinInfo;let close = document.querySelector("#close");close.onclick = () => {// state.map.removeOverLay(state.customerWinInfo);state.map.clearOverLays();addMarker();};let showTrack = document.querySelector("#showTrack");showTrack.onclick = () => {showcarguiji(v);};}//查看车辆轨迹function showcarguiji(v) {state.v = v;state.startgj = true;state.carTrack = true;state.name = v.carcode;state.timeDate.date = moment().format("YYYY-MM-DD");state.timeDate.startTime = "00:00:00";state.timeDate.endTime = "23:59:59";state.timeList = [];//由于使用ctx 打包后会保存,暂用jquery代替$('#mapDiv').hide()$('#guijimap').show()// ctx.$refs.mapDiv.style.display="none";// ctx.$refs.guijimap.style.display = "block";//初始化地图对象var map1 = new TMap("guijimap");//设置显示地图的中心点和级别map1.centerAndZoom(new TLngLat(119.96529, 30.54044), 16);//允许鼠标滚动放大地图map1.enableHandleMouseScroll();map1.clearOverLays();state.map1 = map1;UrGban();carvehicle(v.devicecode);}function startTrack() {console.log("start");var map1 = state.map1;var linebottom = state.linebottom;state.startgj = false;clearInterval(state.timename);state.timename = setInterval(function() {var st = Math.ceil(state.timeDate.rangeValue / 9);var timehms = moment(state.startGTime).subtract(-st, "second").format("HH:mm:ss");state.startGTime = moment(state.startGTime).subtract(-st, "second").format("YYYY-MM-DD HH:mm:ss");if (state.markercaruserlinelabel != null)map1.removeOverLay(state.markercaruserlinelabel);timelabel(timehms, state.markercarline.getLngLat());if (state.startGTime >= linebottom[state.iguiji]["time"]) {//当前时间车辆所在位置if (state.markercarline != null)map1.removeOverLay(state.markercarline);state.markercarline = new TMarker(linebottom[state.iguiji]["TLngLat"],{icon: new TIcon(require("../../assets/image/map/point.png"),new TSize(32, 25),{ anchor: new TPixel(16, 25) }), //车辆轨迹});map1.addOverLay(state.markercarline);if (state.markercaruserlinelabel != null)map1.removeOverLay(state.markercaruserlinelabel);timelabel(timehms, state.markercarline.getLngLat());state.iguiji++;if (state.iguiji == linebottom.length) {console.log(123);clearInterval(state.timename);state.startgj = true;state.iguiji = 0;state.closetimeinter = 0;state.startGTime = linebottom[0]["time"];}}}, state.setCarTnterTime);state.closetimeinter = 1;//添加起始车辆位置点标注console.log("end");}function pauseTrack() {clearInterval(state.timename);state.startgj = true;state.closetimeinter = 0;}function stopTrack() {state.iguiji = 0;state.closetimeinter = 0;state.startGTime = state.linebottom[0]["time"];clearInterval(state.timename);state.startgj = true;var lastm = state.linebottom.length - 1;if (state.markercarline != null)state.map1.removeOverLay(state.markercarline);if (state.markercaruserlinelabel != null)state.map1.removeOverLay(state.markercaruserlinelabel);state.markercarline = new TMarker(state.linebottom[lastm]["TLngLat"], {icon: new TIcon(require("../../assets/image/map/point.png"),new TSize(32, 25),{ anchor: new TPixel(16, 25) }),});state.map1.addOverLay(state.markercarline);timelabel(moment(state.linebottom[lastm]["time"]).format("HH:mm:ss"),state.linebottom[lastm]["TLngLat"]);}function sliderChange(val) {state.setCarTnterTime = 1000 / val;var st = Math.ceil(val / 9);var map1 = state.map1;var linebottom = state.linebottom;if (state.closetimeinter == 1) {clearInterval(state.timename);state.timename = setInterval(function() {var timehms = moment(state.startGTime).subtract(-st, "second").format("HH:mm:ss");state.startGTime = moment(state.startGTime).subtract(-st, "second").format("YYYY-MM-DD HH:mm:ss");if (state.markercaruserlinelabel != null)map1.removeOverLay(state.markercaruserlinelabel);timelabel(timehms, state.markercarline.getLngLat());if (state.startGTime >= linebottom[state.iguiji]["time"]) {//当前时间车辆所在位置if (state.markercarline != null)map1.removeOverLay(state.markercarline);state.markercarline = new TMarker(linebottom[state.iguiji]["TLngLat"],{icon: new TIcon(require("../../assets/image/map/point.png"),new TSize(32, 25),{ anchor: new TPixel(16, 25) }),});map1.addOverLay(state.markercarline);if (state.markercaruserlinelabel != null)map1.removeOverLay(state.markercaruserlinelabel);timelabel(timehms, state.markercarline.getLngLat());state.iguiji++;if (state.iguiji == linebottom.length) {clearInterval(state.timename);state.startgj = true;state.iguiji = 0;state.closetimeinter = 0;state.startGTime = linebottom[0]["time"];}}}, state.setCarTnterTime);}}function timelabel(timehms, position) {var config = {text:'' +timehms +"",offset: new TPixel(0, 0),position: position,};state.markercaruserlinelabel = new TLabel(config); //创建地图文本对象state.markercaruserlinelabel.setAnchorPer([0.5, 2]); //偏移量state.markercaruserlinelabel.setBorderLine(0);state.markercaruserlinelabel.setFontColor("#FFFFFF");state.markercaruserlinelabel.setBackgroundColor("transparent");state.map1.addOverLay(state.markercaruserlinelabel);}// ******************** 播放轨迹 查询轨迹var carline = null;function carvehicle(v_devicecode, start_time, end_time) {state.map1.removeOverLay(state.markercarline);state.map1.removeOverLay(state.carline);state.map1.removeOverLay(state.markercaruserlinelabel);if (!start_time) {var fields = {deviceCode: v_devicecode,mapType: "aMap",startTime: moment().format("YYYY-MM-DD") + " 00:00:00",endTime: moment().format("YYYY-MM-DD HH:mm:ss"),};} else {var fields = {deviceCode: v_devicecode,mapType: "aMap",startTime: start_time,endTime: end_time,};}getcartrajectory_by_cid_time(fields).then((res) => {if (res.responseCode == 0) {var linebottom = [];var linebottompoint = [];if (res.data) {var knum = 0;res.data.map((v, k) => {if (v["longitudedone"]) {var arr = new Object();arr["TLngLat"] = new TLngLat(v["longitudedone"],v["latitudedone"]);arr["time"] = format(v["equipmenttime"]);linebottom[knum] = arr;linebottompoint.push(new TLngLat(v["longitudedone"], v["latitudedone"]));state.timeList = linebottom;knum++;}});state.linebottom = linebottom;state.markercarline = new TMarker(linebottompoint[0], {icon: new TIcon(require("../../assets/image/map/point.png"),new TSize(32, 25),{ anchor: new TPixel(16, 25) }), //车辆轨迹});state.map1.addOverLay(state.markercarline);state.startGTime = linebottom[0]["time"];// 添加其实车辆位置点标注//创建线对象carline = new TPolyline(linebottompoint, {strokeColor: "blue",strokeWeight: 2,strokeOpacity: 1,});state.carline = carline;//向地图上添加线state.map1.addOverLay(carline);state.map1.setViewport(linebottompoint);state.map1.panTo(linebottompoint[0]);timelabel(moment(linebottom[0]["time"]).format("HH:mm:ss"),state.markercarline.getLngLat());} else {message.error("暂无数据!");}}});// .catch(()=>{// alert('网络请求失败,请稍后再试');// })}function clickCar(v, k) {console.log(v);let map1 = state.map1;map1.panTo(v["TLngLat"]);state.iguiji = k;state.startGTime = moment(v.time).format("YYYY-MM-DD HH:mm:ss");state.closetimeinter = 0;clearInterval(state.timename);if (state.markercarline != null) map1.removeOverLay(state.markercarline);if (state.markercaruserlinelabel != null)map1.removeOverLay(state.markercaruserlinelabel);state.markercarline = new TMarker(v["TLngLat"], {icon: new TIcon(require("../../assets/image/map/point.png"),new TSize(32, 25),{ anchor: new TPixel(16, 25) }),});map1.addOverLay(state.markercarline);timelabel(moment(v.time).format("HH:mm:ss"),state.markercarline.getLngLat());}function DeleteInfoBox() {if (state.customerWinInfo.point != undefined)state.map.removeOverLay(state.customerWinInfo);}function UrGban() {//创建标注对象var marker = new TMarker(new TLngLat(119.95777, 30.53184), {icon: state.cgjicon,});//向上地图上添加标注state.map1.addOverLay(marker);}function carTrackReturn() {$('#mapDiv').show()$('#guijimap').hide()// ctx.$refs.mapDiv.style.display = "block";// ctx.$refs.guijimap.style.display = "none";state.carTrack = false;}function dateTimeChange(a, date, dateString) {let startTime, endTime;switch (a) {case 1:state.timeDate.date = date.format("YYYY-MM-DD");break;case 2:open1.value = false;break;case 3:open2.value = false;break;default:break;}startTime = state.timeDate.date + " " + state.timeDate.startTime;endTime = state.timeDate.date + " " + state.timeDate.endTime;carvehicle(state.v.devicecode, startTime, endTime);}const handleMenuClick = (e) => {let v = state.carList[e.key];if (v.longitude != undefined) {state.map.clearOverLays();let lngLat = new TLngLat(v.longitude, v.latitude);state.map.panTo(lngLat);//创建标注对象var icont = new TIcon(require("../../assets/image/map/caricon_10.png"),new TSize(28, 38),{anchor: new TPixel(12, 30),});state.icont = icont;let marker = new TMarker(lngLat, {icon: icont,});//向上地图上添加标注state.map.addOverLay(marker);//注册标注的点击事件TEvent.addListener(marker, "click", function() {showonecarinfo(v, this);});showonecarinfo(v, marker);} else {message.error("暂无轨迹!");}};const disabledDate = (current) => {return current > moment().endOf("day");};const onChange = (value, dateString) => {console.log("Selected Time: ", value);console.log("Formatted Selected Time: ", dateString);};const onOk = (value) => {console.log("onOk: ", value);};return {...toRefs(state),initMap,initMapHeight,getData,disabledDate,onChange,onOk,startTrack,open1,open2,clickCar,pauseTrack,stopTrack,sliderChange,carTrackReturn,dateTimeChange,handleMenuClick,locale,moment};},
});
</script><style lang="less" scoped>
#mapDiv,
#guijimap {width: 100%;height: 100%;overflow: hidden;
}.drapdown_wrap {position: absolute;left: 0px;top: 160px;z-index: 400;width: 200px;// height: 300px;background-color: #fff;.dropdown {width: 100%;z-index: 99999;background-color: #006dc9;color: #fff;}
}
@media (min-width: 1664px) {.drapdown_wrap {position: absolute;left: 0px;top: 160px;}/*轨迹选择时间弹框*/.tabbable-line.guijitabbox {position: fixed;right: 10px;top: 151px;width: 358px;z-index: 999;background: #fff;color: #5f5f5f;box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.5);border-radius: 0 0 3px 3px !important;overflow: hidden;}/*弹框中的input*/.form-group .col-sm-7 {padding-left: 0 !important;}/*查询轨迹*/.gjtimelist {border-bottom: 1px dashed #e3e3e3;cursor: pointer;}.guijinumlist {padding: 2px 8px 2px 4px;background: #89bff5;color: #fff;margin-right: 10px;}.backspan {font-size: 14px;margin-left: 10px;cursor: pointer;}/*巡检路线*/.tabselbox {height: 372px;border-top: 1px solid #999;text-align: left;padding: 7px 15px;}.tabselbox > a {display: block;color: #000;cursor: pointer;border-bottom: 1px dashed #ccc;padding: 9px 10px 0;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.tabselbox > a:hover {color: #5b9bd1;}
}
@media (max-width: 1664px) {.drapdown_wrap {position: absolute;left: 0px;top: 124px;}/*轨迹选择时间弹框*/.tabbable-line.guijitabbox {position: fixed;right: 10px;top: 119px;width: 358px;z-index: 999;background: #fff;color: #5f5f5f;box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.5);border-radius: 0 0 3px 3px !important;overflow: hidden;}/*弹框中的input*/.form-group .col-sm-7 {padding-left: 0 !important;}/*查询轨迹*/.gjtimelist {border-bottom: 1px dashed #e3e3e3;cursor: pointer;}.guijinumlist {padding: 2px 8px 2px 4px;background: #89bff5;color: #fff;margin-right: 10px;}.backspan {font-size: 14px;margin-left: 10px;cursor: pointer;}/*巡检路线*/.tabselbox {height: 372px;border-top: 1px solid #999;text-align: left;padding: 7px 15px;}.tabselbox > a {display: block;color: #000;cursor: pointer;border-bottom: 1px dashed #ccc;padding: 9px 10px 0;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.tabselbox > a:hover {color: #5b9bd1;}
}</style><style >.isonlines {color: #006dc9 !important;}
</style>
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
