首先封装初始化
export default {
init: function (){
const AK = "XCQBZ-E4N6W-PDPR4-OYAVJ-ON7KQ-NKBCD";
const TMap_URL = "https://map.qq.com/api/gljs?v=1.exp&libraries=tools,service,geometry&key="+ AK +"&callback=onMapCallback";
return new Promise((resolve, reject) => {
// 如果已加载直接返回
if(typeof TMap !== "undefined") {
resolve(TMap);
return true;
}
// 地图异步加载回调处理
window.onMapCallback = function () {
resolve(TMap);
};
// 插入script脚本
let scriptNode = document.createElement("script");
scriptNode.setAttribute("type", "text/javascript");
scriptNode.setAttribute("src", TMap_URL);
document.body.appendChild(scriptNode);
});
}
}
正式使用
HTML内容
<template>
<div class="container">
<div id="map"></div>
<el-button size="mini" type="success" plain @click="resetMap">重置地图</el-button>
<el-button size="mini" type="success" plain @click="startDraw">开始绘制</el-button>
<el-button size="mini" type="success" plain @click="stopDraw">停止绘制</el-button>
<el-button size="mini" type="success" plain @click="activeDraw">编辑区域</el-button>
<el-button size="mini" type="success" plain @click="deleteDraw" v-if="showEditToolBottom">删除</el-button>
<!-- <el-button size="mini" @click="splitDraw" v-if="showEditToolBottom">拆分</el-button> -->
<!-- <el-button size="mini" @click="unionDraw" v-if="showEditToolBottom">合并</el-button> -->
</div>
</template>
JS部分
<script>
import TMap from "@/utils/initMap";
export default {
name: 'tencenteMap',
data() {
return {
TXMap:null,
tMap:null,
markerLayer:null,
markersData:[
{id:1,category:'lj',lat:'23.010417',lon:'113.759210',categoryName:'鸿福路地铁站',number:1,status:0},
{id:2,category:'ej',lat:'23.020157',lon:'113.767954',categoryName:'旗峰公园地铁站',number:1,status:0},
{id:3,category:'ej',lat:'23.015321',lon:'113.744150',categoryName:'莱蒙商业中心',number:1,status:0},
{id:4,category:'ej',lat:'23.030448',lon:'113.757773',categoryName:'恒丰商业大厦',number:1,status:0}
],
typeOptions:[
{id:1,src:'~@/../public/marker.png'},
{id:2,src:'~@/../public/marker.png'},
],
infoWin: null, // 信息窗口实例
editor:null,
drawId:[],
showEditToolBottom:false,
drawList:[],
carPath:[],
polylineLayer:null
}
},
mounted() {
this.$nextTick(()=>{
this.init()
setTimeout(()=>{
this.renderMarker()
},250)
})
},
methods: {
init(){
TMap.init().then((TMap) => {
this.TXMap = TMap;
this.tMap = new TMap.Map("map", {
center: new TMap.LatLng(23.020853,113.751861), //设置地图中心点坐标
zoom: 14, //设置地图缩放级别
viewMode: "2D",
});
});
},
startDraw(){ //开始绘制多边形
this.showEditToolBottom = false
this.drawCpmlete()
},
stopDraw(){ //停止绘制多边形
this.showEditToolBottom = false
this.editor.destroy()
},
resetMap(){ //销毁,重置地图
this.showEditToolBottom = false
this.drawId = []
this.tMap.destroy()
this.$nextTick(()=>{
this.init()
setTimeout(()=>{
this.renderMarker()
},250)
})
},
//调用本函数,激活编辑工具绘制状态,开始绘制
activeDraw(){
if(this.drawId.length<=0){
this.$message.error('请先绘制区域后再进行编辑操作')
return
}
if(!this.editor){
this.$message.error('请先开始绘制')
return
}
this.showEditToolBottom = true
this.editor.setActionMode(1).select(this.drawId).setSelectable(true);
//参数中的"polygon133"即为要进行编辑的MultiPolygon的id(注意方代码有定义)
// 监听删除、修改、拆分、合并完成事件
let evtList = ['delete', 'adjust', 'split', 'union'];
evtList.forEach(evtName => {
this.editor.on(evtName + '_complete', evtResult => {
console.log(evtName, evtResult);
});
});
// 监听拆分失败事件,获取拆分失败原因
this.editor.on('split_fail', (res) => {
console.log(res)
});
// 监听合并失败事件,获取合并失败原因
this.editor.on('union_fail', (res) => {
console.log(res)
});
// 监听删除完成,清除对应数据
this.editor.on('delete_complete', (res) => {
res.forEach((item,indexs)=>{
let index = this.drawList.findIndex(items=>items.drawId==item.id)
if(index >=0){
this.drawList.splice(index,1)
}
let idIndex = this.drawId.findIndex(items=>items == item.id)
if(idIndex >=0){
this.drawId.splice(idIndex,1)
}
})
this.$message.success('删除成功')
});
// 修改完成,调整对应数据
this.editor.on('adjust_complete', (geometry) => {
let drawAreaCustomer=[]
let msg = ''
this.markersData.forEach((item,index)=>{
let checkInsite = this.TXMap.geometry.isPointInPolygon(new this.TXMap.LatLng(item.lat*1, item.lon*1),geometry.paths)
if(checkInsite){
drawAreaCustomer.push(item)
msg += ','+item.categoryName
}
})
let nowDraw = this.drawList.find(items=>items.id==geometry.id)
if(nowDraw){
nowDraw.latLng = geometry.paths
nowDraw.drawAreaCustomer = drawAreaCustomer
}
if(msg == ''){
this.$message.error('修改后区域内没有客户')
}else{
this.$message.success('修改后选中的客户有'+msg)
}
});
},
//拆分多边形
splitDraw(){
this.editor.split()
},
//合并多边形
unionDraw(){
this.editor.union()
},
//删除多边形
deleteDraw(){
this.editor.delete()
},
//多边形绘制
drawCpmlete(){
let map = this.tMap
this.editor = new this.TXMap.tools.GeometryEditor({
map, // 编辑器绑定的地图对象
overlayList: [ // 可编辑图层
{
//GeometryEditor 以 MultiPolygon(可以理解为多边形图层)激活进行编辑
id: 'polygon133',
overlay: new this.TXMap.MultiPolygon({
map,
}),
}
],
actionMode: this.TXMap.tools.constants.EDITOR_ACTION.DRAW, //编辑器的工作模式
snappable: true // 开启邻近吸附
});
// 监听绘制结束事件,获取绘制几何图形
this.editor.on('draw_complete', (geometry) => {
this.drawId.push(geometry.id)
let drawAreaCustomer=[]
let msg = ''
this.markersData.forEach((item,index)=>{
let checkInsite = this.TXMap.geometry.isPointInPolygon(new this.TXMap.LatLng(item.lat*1, item.lon*1),geometry.paths)
if(checkInsite){
drawAreaCustomer.push(item)
msg += ','+item.categoryName
}
})
let data = {
drawId:geometry.id,
latLng:geometry.paths,
drawAreaCustomer:drawAreaCustomer
}
this.drawList.push(data)
if(msg == ''){
this.$message.error('该区域内没有客户')
}else{
this.$message.success('当前选中的客户有'+msg)
}
});
},
// 将坐标点处理为地图可以识别的坐标
hanleMarker() {
let myMarkers = [];
this.markersData.map((item, index) => {
let obj = {
id: item.id,
styleId: "marker" + item.category,
position: new this.TXMap.LatLng(item.lat * 1, item.lon * 1),
properties: {
title: `${item.categoryName}`,
status: item.status,
},
};
myMarkers.push(obj);
});
return myMarkers;
},
renderMarker() {
let markerArr = this.hanleMarker();
let map = this.tMap;
this.marker = new this.TXMap.MultiMarker({
id: "marker-layer",
map: map,
styles: this.setMarkImg(),
geometries: markerArr,
});
//给标识添加点击事件
this.marker.on("click", (event) => {
console.log(event)
let { lat, lng } = event.latLng;
let { title, status } = event.geometry.properties;
this.initWindow(lat, lng, title, status);
this.infoWin.open();
});
},
setMarkImg() {
let styleOption = {};
// 遍历图标集合
this.typeOptions.map((item) => {
styleOption["marker" + item.id] = new this.TXMap.MarkerStyle({
cursor: "pointer",
width: 25,
height: 25,
anchor: { x: 16, y: 32 },
src: item.active_icon,
});
});
return styleOption;
},
// 初始化一个信息窗口
initWindow(lat, lng, title, status) {
// 一次只能打开一个窗口 打开之前先关闭之前打开的
if (this.infoWin) {
this.closeWindow();
}
this.infoWin = new this.TXMap.InfoWindow({
map: this.tMap,
position: new this.TXMap.LatLng(lat, lng),
// enableCustom: true,
content: title,
offset: { x: 0, y: -30 }, //设置信息窗相对position偏移像素
});
// 信息窗口关闭回调
this.infoWin.on("closeclick", () => {
// ...
});
},
// 关闭信息窗口
closeWindow() {
if (this.infoWin) {
this.infoWin.close();
}
}
}
}
</script>