Vue-腾讯地图的使用

3,613 阅读2分钟

这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战

最近项目中遇到了需要在地图上规划线路,修改线路,查看线路,标注点,修改点,查看点的需求,认真研究了腾讯地图官网之后,有了一点心得,总结一下,(本文只说实战经验,具体的文档属性,官网很清楚的),温故而知新! 要实现如下的地图,包括了:

1.png

一.绘制线

1.绘制线路,拖动线路可编辑,双击可删除节点

  • html部分
<div class="mapContainer">
    <span>公里:{{distanceDraw}}公里</span>
    <el-button size="mini" type="primary" @click="delPolygon" class="btn" v-if="!disabled">重新绘制</el-button>
    <div id="mapItem" class="mapBox" :style="{
            width: mapStyle.width,
            height: mapStyle.height,
         }"></div>
</div>
  • js部分,定义变量
data() {
    return {
        paths: [],// 线路节点
        longitude: '118.90581786632538',// 经度
        latitude: '31.912693393211505',// 纬度
        lngLatData: [], // 绘制多边形坐标点
        distanceDraw: 0,// 绘制距离
        lines: '',
    };
},
props: {
    latLng: Array,
    distance: {
        type: String,
        default: ''
    },
    center: Array,
    zoom: {
        type: Number,
        default: 13,
    },
    mapStyle:{
        type:Object,
        default(){
            return{
                width: '100%',
                height: '550px',
            }
        }
    },
    disabled: Boolean,
},
  • 引入所需js ,按需引入需要的js(key需要自己去申请一个)
loadMap() {
    return new Promise(function(resolve, reject) {
        let script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://map.qq.com/api/gljs?libraries=geometry&v=2.exp&key="+ baseMapKey;
        script.onerror = reject;
        document.head.appendChild(script);
        let script2 = document.createElement("script");
        script2.type = "text/javascript";
        script2.src = "https://map.qq.com/api/js?v=2.exp&libraries=drawing&key="+ baseMapKey;
        script2.onerror = reject;
        document.head.appendChild(script2);
        resolve();
    });
},
  • 地图初始化
init() {
    if(this.center && this.center.length > 0) {
        this.latitude = this.center[0];
        this.longitude = this.center[1];
    }
    this.distanceDraw = this.distance || 0;
    zoomLevel = this.zoom || 13;
    // 地图初始化
    map = new window.qq.maps.Map(document.getElementById('mapItem'), {
        center: new window.qq.maps.LatLng(this.latitude,this.longitude),
        zoom: this.zoom, // 设置地图缩放级别
        scrollwheel: false,
        scaleControl: true,//启用比例尺
        scaleControlOptions: {
            //设置控件位置相对右下角对齐,向左排列
            position: window.qq.maps.ControlPosition.BOTTOM_RIGHT
        },
        zoomControl: true,
        //设置缩放控件的位置和样式
        zoomControlOptions: {
            //设置缩放控件的位置为相对左方中间位置对齐.
            position: window.qq.maps.ControlPosition.TOP_LEFT,
            //设置缩放控件样式为仅包含放大缩小两个按钮
            style: window.qq.maps.ZoomControlStyle.LARGE
        },
        panControl: true,// 平移控件
        mapTypeControl: false,// 默认是地图和卫星
    });
    let that = this;
    window.qq.maps.event.addListener(map,'zoom_changed',()=> {
        zoomLevel = map.getZoom();
        that.$emit('saveLatLng', null, null, zoomLevel);
    });

    // 回显线路
    if(this.latLng && this.latLng.length > 0){
        let path = [];
        this.latLng.forEach(item => {
            path.push(new window.qq.maps.LatLng(item.lat,item.lng));
        });
        this.getLine(path);
    }else {
        // 绘图工具
        this.getDrawMan();
    }
},
  • 获取绘图工具,设置绘图属性
getDrawMan() {
    // 绘图工具
    drawingManager = new window.qq.maps.drawing.DrawingManager({
        drawingMode: window.qq.maps.drawing.OverlayType.POLYLINE,
        // 是否启用DrawingManager地图控件,默认为false
        // drawingControl: true,
        // 设置DrawingManager地图控件的参数
        drawingControlOptions: {
            position: window.qq.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
                window.qq.maps.drawing.OverlayType.POLYLINE,
            ]
        },
        // 绘制polyline的属性
        polylineOptions: {
            strokeLinecap: 'square',// 折线末端线帽的样式,圆形为round(默认),方形为square,平直为butt。
            strokeColor: new window.qq.maps.Color(0,0,0,1),
            strokeWeight: 5,
            strokeDashStyle: 'solid',// 折线的形状。实线是solid,虚线是dash。
            clickable: true,// 折线是否可点击
            editable: true,
        },
        snapMode: true,
    });
    drawingManager.setMap(map);
    // 绘制完成
    window.qq.maps.event.addListener(drawingManager, 'polylinecomplete', (event)=> {
        this.getDistance(event.getPath().elems);
        this.$emit('saveLatLng',event.getPath().elems, this.distanceDraw, zoomLevel);
        drawingManager.setDrawingMode(null);// 清除绘制模式
        this.lines = event;
        polyline = null;
    })
},
  • 计算路径的实际距离
getDistance(paths) {
    let distance = 0;
    let startPoint = new window.TMap.LatLng(paths[0].lat, paths[0].lng);
    let endPoint = '';
    for(let i = 1;i < paths.length; i++){
        endPoint = new window.TMap.LatLng(paths[i].lat, paths[i].lng);
        let path = [startPoint, endPoint];
        distance += window.TMap.geometry.computeDistance(path);
        startPoint = endPoint;
    }
    this.distanceDraw = (distance / 1000).toFixed(2);
},

2.重新绘制

  • 删除初始化多边形,即重新绘制
delPolygon() {
    if(polyline){
        polyline.setMap(null);
    }else{
        this.lines.setMap(null);
    }
    this.getDrawMan();
    this.distanceDraw = 0;
    this.$emit('saveLatLng',[], '0', zoomLevel);
},

3.编辑回显线路,修改线路

  • 绘制线路,新增,修改,删除节点
getLine(path){
    polyline = new window.qq.maps.Polyline({
        path: path,// 折线的路径,以经纬度坐标数组构成
        strokeColor: '#000',
        strokeWeight: 5,
        map: map,// 要显示折线的地图
        clickable: true,// 折线是否可点击
        editable: !this.disabled,// 启动编辑功能后,可拖动端点对折线进行调整,双击节点可删除
        zIndex: 1000,
    });
    let _this = this;
    // 新增节点
    window.qq.maps.event.addListener(polyline,"insertNode",function(event){
        _this.getDistance(event.path.elems);
        _this.$emit('saveLatLng',event.path.elems, this.distanceDraw, zoomLevel);
    });
    // 移动节点
    window.qq.maps.event.addListener(polyline,"adjustNode",function(event){
        _this.getDistance(event.path.elems);
        _this.$emit('saveLatLng',event.path.elems, this.distanceDraw, zoomLevel);
    });
    // 删除节点
    window.qq.maps.event.addListener(polyline,"removeNode",function(event){
        _this.getDistance(event.path.elems);
        _this.$emit('saveLatLng',event.path.elems, this.distanceDraw, zoomLevel);
    });
},

二.绘制点

其中html,js属性,引入js如上线的,下面说一下不一样的地方

1.绘制点

  • 地图初始化
init() {
    map = new window.qq.maps.Map(document.getElementById('mapItem'), {
        center: new window.qq.maps.LatLng(this.latitude,this.longitude),
        zoom: 13, // 设置地图缩放级别
        scaleControl: true,//启用比例尺
        scaleControlOptions: {
            // 设置控件位置相对右下角对齐,向左排列
            position: window.qq.maps.ControlPosition.BOTTOM_RIGHT
        },
        scrollwheel: false,
        zoomControl: true,
        // 设置缩放控件的位置和样式
        zoomControlOptions: {
            // 设置缩放控件的位置为相对左方中间位置对齐.
            position: window.qq.maps.ControlPosition.TOP_LEFT,
            // 设置缩放控件样式为仅包含放大缩小两个按钮
            style: window.qq.maps.ZoomControlStyle.LARGE
        },
        panControl: true,// 平移控件
        mapTypeControl: false,// 默认是地图和卫星
    });
    window.qq.maps.event.addListener(map,'zoom_changed',function() {
        zoomLevel = map.getZoom();
    });
    // 添加dom监听事件
    window.qq.maps.event.addListener(map, 'click', (event)=> {
        if(!marker){
            this.addMarker(event.latLng, 1);
        }
        marker.setPosition(event.latLng);
        this.$emit('saveLatLng',event.latLng, zoomLevel);
    });
    if(this.latLng.latitude !== '' && this.latLng.latitude !== null) {
        let location = new window.qq.maps.LatLng(this.latLng.latitude,this.latLng.longitude);
        this.addMarker(location);
        marker.setPosition(location);
    }
},

2.重新绘制

  • 删除标记
// 删除标记
deleteOverlays(flag) {
    if (markerArray) {
        for (let i in markerArray) {
            markerArray[i].setMap(null);
        }
        marker = null;
        markerArray.length = 0;
        if(flag == 1){
            this.$emit('saveLatLng',null, zoomLevel);
        }
    }else {
        this.$message({
            message: '删除失败,请先标记一个位置',
            type: 'error',
        });
    }
},

3.编辑回显点,修改点

  • 添加标记
// 添加标记
addMarker(location) {
    marker = new window.qq.maps.Marker({
        icon: new window.qq.maps.MarkerImage(
        require('@/assets/images/marker_blue.png'),new window.qq.maps.Size(50, 50)),
        position: location,
        map: map
    });
    markerArray = [marker];
},

文章最后,送给大家一颗小心心!

2.png

如上就是在项目中使用腾讯地图的全部代码了,谢谢观看!