vue高德多条路线规划+带途径节点多组多个maker + maker批量带各自鼠标移入移出监听事件(对应的text标签显示与隐藏)+各路线颜色区别(版本三)

2023-11-10

一 功能介绍:

vue高德批量路线规划+多组路线带途径节点marker+ maker批量带各自鼠标移入移出监听事件(对应的text标签显示与隐藏)+各路线不同颜色显示+各marker带点击监听事件(显示途径点详细内容)

版本三:各线路上批量的marker各单个maker 的 鼠标监听移入移出事件( mouseover、mouseout) 对应控制各自 另外各自对应创建text标签 的显示与隐藏 功能

效果图:

鼠标移入站点 显示站点(maker) 对应的 站点名称(text),鼠标移出站点 则隐藏

点击某个站点 生成规划同一路线上站点的路线

二、实现

1.本项目使用的 高德api 故需要申请高德web开发相关申请配置 见这篇

2.oneSelectCharts.vue 地图渲染图组件

<template>
  <div class="clearFix">
    <div id="mapAmap" class="clearFix card-shadow">
      <div class="clearFix">
        <canvas></canvas>
      </div>
    </div>
    <div id="panel0"></div>
  </div>
</template>

<script>
  // import AMap from 'AMap'
  const AMap = window.AMap
  // import AMapUI from 'AMapUI'
  export default {
    name: '',
    props: [],
    components: { },
    data() {
      return {
        // imgUrlDriver: require('@/assets/car/car_two.png'),
        lineName: '车次', // 线路
    colors: ['#DC143C', '#5F9EA0', '#00BFFF', '#C71585', '#6495ED',
          '#008B8B', '#FFFF00', '#FFD700', '#FFDEAD', '#FF4500',
          '#FF8C00', '#8B4513', '#FFF5EE', '#FF7F50', '#FF6347','#7B68EE',
  '#483D8B','#4169E1','#4682B4','#00FF7F','#7FFF00','#FAFAD2','#F0E68C','#FA8072','#FF69B4'], // 25个颜色
        colorsNum: 25
      }
    },
    mounted() {
      // this.getList()
    },
    methods: {
      initDataFunc() {
        const that = this
        // 所有需要绘制的相关总数据(包含绘制路线的数据)
        const data1 = [
          {
          "id": 1111116,
          "trainWaybillDtoList": [{
            "id": null,
            "sort": null,
            "waybillNum": null,
            "trainUuid": null,
            "receivingAddr": "xxxx物流公明基地",
            "externalNum": null,
            "longitude": "113.922500",
            "latitude": "22.750898",
            "startAddr": null,
            "startLongitude": null,
            "startLatitude": null
          },
            {
              "id": 1111116,
              "sort": 0,
              "waybillNum": "YD20200903032358186749616",
              "trainUuid": "C20200903035229183987",
              "receivingAddr": "陈庄奋(惠达商行)",
              "externalNum": "3124353",
              "longitude": "113.828463",
              "latitude": "22.693852",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            },
            {
              "id": 1111116,
              "sort": 1,
              "waybillNum": "YD20200903032358305204187",
              "trainUuid": "C20200903035229183987",
              "receivingAddr": "育城大华业",
              "externalNum": "3114225",
              "longitude": "113.820547",
              "latitude": "22.691868",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            },
            {
              "id": 1111116,
              "sort": 2,
              "waybillNum": "YD20200903032358283570912",
              "trainUuid": "C20200903035229183987",
              "receivingAddr": "巧忠盛店",
              "externalNum": "3114381",
              "longitude": "113.817378",
              "latitude": "22.695533",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            }],
          "trainUuid": "C2020090303522918398721"
        },
          {
            "id": 1111114,
            "trainWaybillDtoList": [{
              "id": null,
              "sort": null,
              "waybillNum": null,
              "trainUuid": null,
              "receivingAddr": "xxxx物流公明基地",
              "externalNum": null,
              "longitude": "113.922500",
              "latitude": "22.750898",
              "startAddr": null,
              "startLongitude": null,
              "startLatitude": null
            },
              {
                "id": 1111114,
                "sort": 0,
                "waybillNum": "YD20200902195057548075800",
                "trainUuid": "C20200903035229168916",
                "receivingAddr": "伟吴大商店",
                "externalNum": "3126814",
                "longitude": "113.881283",
                "latitude": "22.565248",
                "startAddr": "xxxx物流公明基地",
                "startLongitude": "113.922500",
                "startLatitude": "22.750898"
              },
              {
                "id": 1111114,
                "sort": 1,
                "waybillNum": "YD20200902195057059284632",
                "trainUuid": "C20200903035229168916",
                "receivingAddr": "唐永元福",
                "externalNum": "3113809",
                "longitude": "113.880512",
                "latitude": "22.564025",
                "startAddr": "xxxx物流公明基地",
                "startLongitude": "113.922500",
                "startLatitude": "22.750898"
              },
              {
                "id": 1111114,
                "sort": 2,
                "waybillNum": "YD20200902045942673413588",
                "trainUuid": "C20200903035229168916",
                "receivingAddr": "郭财彬",
                "externalNum": "3133420",
                "longitude": "113.870625",
                "latitude": "22.568876",
                "startAddr": "xxxx物流公明基地",
                "startLongitude": "113.922500",
                "startLatitude": "22.750898"
              },
              {
                "id": 1111114,
                "sort": 3,
                "waybillNum": "YD20200902045942562775387",
                "trainUuid": "C20200903035229168916",
                "receivingAddr": "深圳市宝安区西乡利佳荣源商店",
                "externalNum": "1107139",
                "longitude": "113.880421",
                "latitude": "22.573325",
                "startAddr": "xxxx物流公明基地",
                "startLongitude": "113.922500",
                "startLatitude": "22.750898"
              }],
            "trainUuid": "C2020090303522916891622"
          }
        ]
        // 需要进行 绘制路线 的数据
        const data2 = [{
          "id": 1111114,
          "trainWaybillDtoList": [{
            "id": null,
            "sort": null,
            "waybillNum": null,
            "trainUuid": null,
            "receivingAddr": "xxxx物流公明基地",
            "externalNum": null,
            "longitude": "113.922500",
            "latitude": "22.750898",
            "startAddr": null,
            "startLongitude": null,
            "startLatitude": null
          },
            {
              "id": 1111114,
              "sort": 0,
              "waybillNum": "YD20200902195057548075800",
              "trainUuid": "C20200903035229168916",
              "receivingAddr": "伟吴大商店",
              "externalNum": "3126814",
              "longitude": "113.881283",
              "latitude": "22.565248",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            },
            {
              "id": 1111114,
              "sort": 1,
              "waybillNum": "YD20200902195057059284632",
              "trainUuid": "C20200903035229168916",
              "receivingAddr": "唐永元福",
              "externalNum": "3113809",
              "longitude": "113.880512",
              "latitude": "22.564025",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            },
            {
              "id": 1111114,
              "sort": 2,
              "waybillNum": "YD20200902045942673413588",
              "trainUuid": "C20200903035229168916",
              "receivingAddr": "郭财彬",
              "externalNum": "3133420",
              "longitude": "113.870625",
              "latitude": "22.568876",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            },
            {
              "id": 1111114,
              "sort": 3,
              "waybillNum": "YD20200902045942562775387",
              "trainUuid": "C20200903035229168916",
              "receivingAddr": "深圳市宝安区西乡利佳荣源商店",
              "externalNum": "1107139",
              "longitude": "113.880421",
              "latitude": "22.573325",
              "startAddr": "xxxx物流公明基地",
              "startLongitude": "113.922500",
              "startLatitude": "22.750898"
            }],
          "trainUuid": "C2020090303522916891622"
        }]
        const toParams = {
          lineNameStr: 'trainUuid', // lineNameStr 线路名称 所用字段
          spotNameStr: 'receivingAddr', //  spotNameStr 途径站点名称 所用字段
          spotIdKey: 'externalNum', // 途径站点 唯一键
          customIdKey: 'lisaSiteInfo', // map里创建 maker text等对象上携带私货时 自定义私货名称  所用字段
          pathListNameStr: 'trainWaybillDtoList', // pathListNameStr 路径数组 所用字段
        }
     
        // 解决初次 打开 dialog 地图不渲染问题
        // that.$nextTick(() => {
        //   that.$refs.oneSelectChartsRef.initFunc('three', that.tableData, drawLineData, toParams)
        // });
        that.initFunc('three', data1, data2, toParams)
      },
      initFunc(type, data, drawLineData, toChartsParams) {
        console.log('oneSelectCharts-initCharts-type', type)
        const mapObj = new AMap.Map('mapAmap', {
          mapStyle: 'amap://styles/grey',
          // center: new AMap.LngLat(capitals[0].longitude, capitals[0].latitude),
          zoom: 12
        })
        if (type === 'two') {
          mapObj.clearMap() // 清除地图覆盖物
          this.typeTwoFunc(mapObj, data, drawLineData, toChartsParams)
        } else if (type === 'three') {
          this.typeThreeFunc(mapObj, data, drawLineData, toChartsParams)
        } else {
          this.typeOneFunc()
        }
      },
      /**
       * 类型1
       * 默认绘制空地图
       * */
      typeOneFunc() {
        const mapObj = new AMap.Map('mapAmap', {
          zoom: 6
        })
        // 清除地图覆盖物
        mapObj.clearMap()
      },
      /**
       * 类型2
       * 绘制地图 批量原型站点,无路线规划
       * */
      typeTwoFunc(mapObj, lineData, drawLineData, toParams) {
        console.log('typeTwoFunc()')
        const _this = this
        const { lineNameStr, spotNameStr, pathListNameStr, spotIdKey, customIdKey } = toParams
        let Driving_obj = new AMap.Driving({
          map: mapObj, // map 指定将路线规划方案绘制到对应的AMap.Map对象上
        })
        Driving_obj.clear() // 清理
        // let routeLine_obj = {}
        for (let f = 0; f < lineData.length; f++) {
          const item_path = lineData[f][pathListNameStr].filter(item => (item.latitude && item.longitude))
          const now_length = item_path.length
          const item_start_path = item_path[0]
          const item_end_path = item_path[now_length - 1]
          const now_arr = item_path.slice(1, now_length - 1)
          _this.createCircleMarker(mapObj, lineData[f][lineNameStr], now_arr, f, toParams, _this.colors)
          _this.createCircleMarkerOne(mapObj,lineData[f][lineNameStr],item_end_path, '终点', f, toParams, _this.colors)
          _this.createCircleMarkerOne(mapObj,lineData[f][lineNameStr],item_start_path, '起点', f, toParams, _this.colors)
        }
      },
      /**
       * 类型3
       * 绘制地图 批量原型站点,多条路线规划
       * */
      typeThreeFunc(mapObj, lineData, drawLineData, toParams) {
        console.log('typeThreeFunc()')
        const _this = this
        const { lineNameStr, spotNameStr, pathListNameStr, customIdKey } = toParams
        const Driving_obj = new AMap.Driving({
          map: mapObj, // map 指定将路线规划方案绘制到对应的AMap.Map对象上
        })
        // let Driving_obj = {}
        // Driving_obj.clear() // 清理
        for (let f = 0; f < drawLineData.length; f++) {
          const item_path = drawLineData[f][pathListNameStr].filter(item => (item.latitude && item.longitude))
          const now_length = item_path.length
          const item_start_path = item_path[0]
          const item_end_path = item_path[now_length - 1]
          const now_arr = item_path.slice(1, now_length - 1)
          const item_way_path = now_arr.map(item => {
            return new AMap.LngLat(item.longitude, item.latitude)
          })
          AMap.plugin(['AMap.TruckDriving'], function() {
            // 全部路线规划
            Driving_obj.search(
              new AMap.LngLat(item_start_path.longitude, item_start_path.latitude),
              new AMap.LngLat(item_end_path.longitude, item_end_path.latitude),
              { waypoints: item_way_path },
              function(status, result) {
                //  searchResult即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                if (status === 'complete') {
                  if (result.routes && result.routes.length) {
                    _this.drawRoute(mapObj,result.routes[0], f, drawLineData, _this.colors)
                    _this.createSiteTextOne(mapObj,drawLineData[f][lineNameStr],item_end_path, '终点', f, toParams, _this.colors)
                  }
                } else {
                  console.log('获取货车规划数据失败:' + result)
                }
              })
          })
        }
        for (let f = 0; f < lineData.length; f++) {
          const item_path = lineData[f][pathListNameStr].filter(item => (item.latitude && item.longitude))
          const now_length = item_path.length
          const item_start_path = item_path[0]
          const item_end_path = item_path[now_length - 1]
          const now_arr = item_path.slice(1, now_length - 1)
          _this.createCircleMarker(mapObj, lineData[f][lineNameStr], now_arr, f, toParams, _this.colors)
          _this.createCircleMarkerOne(mapObj,lineData[f][lineNameStr],item_end_path, '终点', f, toParams, _this.colors)
          _this.createCircleMarkerOne(mapObj,lineData[f][lineNameStr],item_start_path, '起点', f, toParams, _this.colors)
        }
      },
      /**
       * 创建 自定义text标签(单个)
       * mapObj 地图对象
       * lineName 当前线路名称
       * item 当前线路的 -当前单个途经点
       * type 当前线路的 -当前单个途经点 的类型 -  '终点' '起点'
       * index2 当前第几条线路
       * toParams - toChartsParams
       * colors 自定义颜色集合
       * */
      createSiteTextOne(mapObj,lineName, item, type, index2, toParams, colors) {
        const _this = this
        const { lineNameStr, spotNameStr, pathListNameStr, spotIdKey, customIdKey } = toParams
        let iconUrl = '', siteName = ''
        if (type === '起点') {
          // iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
          siteName = '起点'
        } else if (type === '终点') {
          // iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
          siteName = '终点'
        } else {
          // 途经
          // iconUrl = '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png'
          siteName = '途经点'
        }
        //-------siteText-------
        // label默认蓝框白底左上角显示,样式className为:amap-marker-label
        const siteText = new AMap.Text({
          offset: new AMap.Pixel(0, -40), //设置文本标注偏移量
          text: _this.lineName + ':' + item[lineNameStr],
          zIndex: 52,
          position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
          map: mapObj
        })
        siteText[customIdKey] = item
        // siteText.on('click', clickHandler1) // 给 siteText 绑定带上 InfoWindow 显示事件
        siteText.setMap(mapObj)
      },
      /**
       * 创建 自定义圆形标签(单个)
       * mapObj 地图对象
       * lineName 当前线路名称
       * item 当前线路的 -当前单个途经点
       * type 当前线路的 -当前单个途经点 的类型 -  '终点' '起点'
       * index2 当前第几条线路
       * toParams - toChartsParams
       * colors 自定义颜色集合
       * */
      createCircleMarkerOne(mapObj,lineName, item, type, index2, toParams, colors) {
        const { lineNameStr, spotNameStr, pathListNameStr, spotIdKey, customIdKey } = toParams
        const _this = this
        const circleTexts = []
        let iconUrl = '', siteName = ''
        if (type === '起点') {
          iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
          siteName = '起点'
        } else if (type === '终点') {
          iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
          siteName = '终点'
        } else {
          // 途经
          iconUrl = '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png'
          siteName = '途经点'
        }
        const siteMarker = new AMap.CircleMarker({
          map: mapObj,
          center: new AMap.LngLat(item.longitude, item.latitude),
          fillColor: colors[(index2 % _this.colorsNum)],
          fillOpacity: 1,
          strokeColor: '#fff',
          strokeOpacity: 1,
          cursor: 'pointer',
          radius: 10,
          zIndex: 10,
          bubble: true
        })
        // 给 Text 带上自定义私货
        siteMarker[customIdKey] = item
        // 监听地图- Text 的 点击事件
        const clickHandler1 = function(e) {
          // log.success("carText模拟触发了地图click事件!");
          console.log('createCircleMarkerOne()-carText模拟触发了地图click事件-e')
          const siteInfo = e.target[customIdKey]
          new AMap.InfoWindow({
            content: lineName + _this.lineName + '</br>' + siteName + '号站点</br>地址:' + siteInfo[spotNameStr]
          }).open(mapObj, e.lnglat)
          // 向父级调用事件
          _this.$emit('site-click', item)
        }
        siteMarker.on('click', clickHandler1)  // 给 siteMarker 绑定带上 InfoWindow 显示事件
        siteMarker.setMap(mapObj)
        //-------siteText-------
        // label默认蓝框白底左上角显示,样式className为:amap-marker-label
        const siteText = new AMap.Text({
          offset: new AMap.Pixel(0, -20),  //设置文本标注偏移量
          text: item[spotNameStr],
          zIndex: 52,
          position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
          map: mapObj
        })
        siteText[customIdKey] = item
        // siteText.on('click', clickHandler1) // 给 siteText 绑定带上 InfoWindow 显示事件
        siteText.setMap(mapObj)
        siteText.hide()
        circleTexts.push(siteText)
        const mouseoverHandler1 = function (e) {
          console.log('text显示')
          _this.showOrHideLabel(e.target[customIdKey], 'mouseover', circleTexts, spotIdKey, spotNameStr, customIdKey);
        }
        const mouseoutHandler1 = function (e) {
          console.log('text隐藏')
          _this.showOrHideLabel(e.target[customIdKey], 'mouseout', circleTexts, spotIdKey, spotNameStr, customIdKey);
        }
        siteMarker.on('mouseover', mouseoverHandler1)
        siteMarker.on('mouseout', mouseoutHandler1)
        return siteMarker
      },
      /**
       * 创建 自定义圆形标签(批量)
       * mapObj 地图对象
       * lineName 当前线路名称
       * now_arr 线路途经点集合
       * index2 当前第几条线路
       * toParams - toChartsParams
       * colors 自定义颜色集合
       * */
      createCircleMarker(mapObj, lineName, now_arr, index2, toParams, colors) {
        const { lineNameStr, spotNameStr, pathListNameStr, spotIdKey, customIdKey } = toParams
        const _this = this
        const middleMarkers = []
        const circleTexts = []
        // -------- 中途 站点-----------
        now_arr.forEach((item, index) => {
          const siteMarker = new AMap.CircleMarker({
            map: mapObj,
            center: new AMap.LngLat(item.longitude, item.latitude),
            fillColor: colors[(index2 % _this.colorsNum)],
            fillOpacity: 1,
            strokeColor: '#fff',
            strokeOpacity: 1,
            cursor: 'pointer',
            radius: 10,
            zIndex: 10,
            bubble: true
          })
          // 给 Text 带上自定义私货
          siteMarker[customIdKey] = item
          // 监听地图- Text 的 点击事件
          const clickHandler1 = function(e) {
            // log.success("carText模拟触发了地图click事件!");
            console.log('createCircleMarker()-carText模拟触发了地图click事件-e')
            const siteInfo = e.target[customIdKey]
            new AMap.InfoWindow({
              content: lineName + _this.lineName + '</br>' + (index + 1) + '号站点</br>地址:' + siteInfo[spotNameStr]
            }).open(mapObj, e.lnglat)
            // 向父级调用事件
            _this.$emit('site-click', item)
          }
          siteMarker.on('click', clickHandler1)  // 给 siteMarker 绑定带上 InfoWindow 显示事件
          siteMarker.setMap(mapObj)
          middleMarkers.push(siteMarker)
          //-------siteText-------
          // label默认蓝框白底左上角显示,样式className为:amap-marker-label
          const siteText = new AMap.Text({
            offset: new AMap.Pixel(0, -20),  //设置文本标注偏移量
            text: item[spotNameStr],
            zIndex: 52,
            position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
            map: mapObj
          })
          siteText[customIdKey] = item
          // siteText.on('click', clickHandler1) // 给 siteText 绑定带上 InfoWindow 显示事件
          siteText.setMap(mapObj)
          siteText.hide()
          circleTexts.push(siteText)
          const mouseoverHandler1 = function (e) {
            console.log('text显示')
            _this.showOrHideLabel(e.target[customIdKey], 'mouseover', circleTexts, spotIdKey, spotNameStr, customIdKey);
          }
          const mouseoutHandler1 = function (e) {
            console.log('text隐藏')
            _this.showOrHideLabel(e.target[customIdKey], 'mouseout', circleTexts, spotIdKey, spotNameStr, customIdKey);
          }
          siteMarker.on('mouseover', mouseoverHandler1)
          siteMarker.on('mouseout', mouseoutHandler1)
        })
        // console.log('middleMarkers', middleMarkers)
        return middleMarkers
      },
      /**
       * 标签对象 上绑定的(鼠标移出移入事件)-是否显示 其对应的 text标题信息
       * mapObj 地图对象
       * itemObj 途径站点 带的私货对象
       * mousetype 鼠标移出类型 'mouseover' 'mouseout'
       * markerSet createCircleMarker内的 text对象的 set集合
       * spotIdKey 站点唯一键 字段
       * spotNameStr 站点名称 字段
       * customIdKey maker、text对象上带的自定义私货 所用字段
       * */
      showOrHideLabel(itemObj, mousetype, markerSet, spotIdKey, spotNameStr, customIdKey) {
        // console.log('showOrHideLabel()-itemObj', itemObj, 'mousetype', mousetype, 'markerSet', markerSet, 'spotIdKey', spotIdKey)
        markerSet.forEach(function (element) {
          if (itemObj[spotIdKey] === element[customIdKey][spotIdKey]) {
            if (mousetype === 'mouseover') {
              element.show()
            } else if (mousetype === 'mouseout') {
              element.hide()
            }
          }
        })
      },
      // 途径节点 marker(集合)- 此处用了 new AMap.Text 需 版本1.4.2
      createMarkerNormal(mapObj, lineName, now_arr, toParams) {
        const { lineNameStr, spotNameStr, pathListNameStr, customIdKey } = toParams
        const _this = this
        const middleMarkers = []
        // -------- 中途 站点-----------
        now_arr.forEach((item, index) => {
          // 创建一个 Icon
          const siteIcon = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(22, 34),
            // 图标的取图地址
            // image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            // image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png',
            // 图标所用图片大小
            imageSize: new AMap.Size(22, 34),
            // 图标取图偏移量
            // imageOffset: new AMap.Pixel(0, 0)
          });
          const siteMarker = new AMap.Marker({
            // text: lineName + '路线-' + (index + 1) + '号站点',
            // icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-' + (index + 1) + '.png',
            icon: siteIcon,
            position: new AMap.LngLat(item.longitude, item.latitude),
            offset: new AMap.Pixel(-10, -32),
            map: mapObj
          })
          // 给 Text 带上自定义私货
          siteMarker[customIdKey] = item
          // 监听地图- Text 的 点击事件
          const clickHandler1 = function(e) {
            // log.success("carText模拟触发了地图click事件!");
            console.log('carText模拟触发了地图click事件-e')
            const siteInfo = e.target[customIdKey]
            new AMap.InfoWindow({
              content: lineName + _this.lineName + '</br>' + (index + 1) + '号站点</br>地址:' + siteInfo[spotNameStr]
            }).open(mapObj, e.lnglat)
            // 向父级调用事件
            _this.$emit('site-click', item)
          }
          siteMarker.on('click', clickHandler1)
          siteMarker.setMap(mapObj)
          middleMarkers.push(siteMarker)
          //-------siteText-------
          // label默认蓝框白底左上角显示,样式className为:amap-marker-label
          const siteText = new AMap.Text({
            offset: new AMap.Pixel(0, -50),  //设置文本标注偏移量
            text: item[spotNameStr],
            zIndex: 52,
            position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
            map: mapObj
          })
          siteText[customIdKey] = item
          siteText.on('click', clickHandler1)
          siteText.setMap(mapObj)
          middleMarkers.push(siteText)
        })
        // console.log('middleMarkers', middleMarkers)
        return middleMarkers
      },
      // 起点 或 终点 marker(单个)
      createMarkerOne(mapObj, lineName, item, type, toParams) {
        const { lineNameStr, spotNameStr, pathListNameStr, customIdKey } = toParams
        const _this = this
        let iconUrl = '', siteName = ''
        if (type === '起点') {
          iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
          siteName = '起点'
        } else if (type === '终点') {
          iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
          siteName = '终点'
        } else {
          // 途经
          iconUrl = '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png'
          siteName = '途经点'
        }
        // -------- 站点-----------
        const oneMarker = new AMap.Marker({
          icon: iconUrl,
          position: new AMap.LngLat(item.longitude, item.latitude),
          offset: new AMap.Pixel(-9, -32),
          map: mapObj
        })
        // 给 Text 带上自定义私货
        oneMarker[customIdKey] = item
        // 监听地图- Text 的 点击事件
        const clickHandler1 = function(e) {
          // log.success("carText模拟触发了地图click事件!");
          console.log('carText模拟触发了地图click事件-e')
          const siteInfo = e.target[customIdKey]
          new AMap.InfoWindow({
            content: lineName + _this.lineName + '</br>' + siteName + '</br>地址:' + siteInfo[spotNameStr]
          }).open(mapObj, e.lnglat)
          // 向父级调用事件
          _this.$emit('site-click', item)
        }
        oneMarker.on('click', clickHandler1)
        oneMarker.setMap(mapObj)
        //-------siteText-------
        // label默认蓝框白底左上角显示,样式className为:amap-marker-label
        const siteText = new AMap.Text({
          offset: new AMap.Pixel(0, -50),  //设置文本标注偏移量
          text: item[spotNameStr],
          zIndex: 52,
          position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
          map: mapObj
        })
        siteText[customIdKey] = item
        siteText.on('click', clickHandler1)
        siteText.setMap(mapObj)
        return oneMarker
      },
      // 行驶路线规划(全部需要行驶的路)
      drawRoute(mapObj, route, index, lineData, colors) {
        const _this = this
        const path = this.parseRouteToPath(route)
        // 生成 折线路线
        const routeLine_obj = new AMap.Polyline({
          map: mapObj,
          zIndex: 51,
          path: path,
          isOutline: true,
          outlineColor: '#ffeeee',
          borderWeight: 0,
          strokeWeight: 6,
          strokeColor: colors[(index % _this.colorsNum)],
          // strokeStyle: 'dashed',
          // lineJoin: 'round'
        })
        routeLine_obj.on('click', function (e, info) {
          console.log('routeLine_obj 模拟触发了地图click事件-e', e, info)
          const pathItem = lineData[index]
          _this.$emit('line-click', pathItem)
        })
        routeLine_obj.setMap(mapObj)
        return routeLine_obj
      },
      // 解析DrivingRoute对象,构造成AMap.Polyline的path参数需要的格式
      // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
      parseRouteToPath(route) {
        const path = []
        for (let i = 0, l = route.steps.length; i < l; i++) {
          const step = route.steps[i]
          for (let j = 0, n = step.path.length; j < n; j++) {
            path.push(step.path[j])
          }
        }
        return path
      },
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  #mapAmap{
    margin: 0 0 0 0;
    width:100%;
    height:900px;
  }
</style>

3.1重点讲解 

createCircleMarker()自定义批量绘制maker方法内 批量绘制 圆形maker(圆圈站点)时候 同时批量(同经纬度位置)绘制text标签(站点名称),并 各个maker上绑定的设置了 鼠标监听(移入移出)事件 mouseoverHandler1() 、mouseoutHandler1()。
/**
       * 创建 自定义圆形标签(批量)
       * mapObj 地图对象
       * lineName 当前线路名称
       * now_arr 线路途经点集合
       * index2 当前第几条线路
       * toParams - toChartsParams
       * colors 自定义颜色集合
       * */
      createCircleMarker(mapObj, lineName, now_arr, index2, toParams, colors) {
        const { lineNameStr, spotNameStr, pathListNameStr, spotIdKey, customIdKey } = toParams
        const _this = this
        const middleMarkers = []
        const circleTexts = []
        // -------- 中途 站点-----------
        now_arr.forEach((item, index) => {
          const siteMarker = new AMap.CircleMarker({
            map: mapObj,
            center: new AMap.LngLat(item.longitude, item.latitude),
            fillColor: colors[(index2 % _this.colorsNum)],
            fillOpacity: 1,
            strokeColor: '#fff',
            strokeOpacity: 1,
            cursor: 'pointer',
            radius: 10,
            zIndex: 10,
            bubble: true
          })
          // 给 Text 带上自定义私货
          siteMarker[customIdKey] = item
          // 监听地图- Text 的 点击事件
          const clickHandler1 = function(e) {
            // log.success("carText模拟触发了地图click事件!");
            console.log('createCircleMarker()-carText模拟触发了地图click事件-e')
            const siteInfo = e.target[customIdKey]
            new AMap.InfoWindow({
              content: lineName + _this.lineName + '</br>' + (index + 1) + '号站点</br>地址:' + siteInfo[spotNameStr]
            }).open(mapObj, e.lnglat)
            // 向父级调用事件
            _this.$emit('site-click', item)
          }
          siteMarker.on('click', clickHandler1)  // 给 siteMarker 绑定带上 InfoWindow 显示事件
          siteMarker.setMap(mapObj)
          middleMarkers.push(siteMarker)
          //-------siteText-------
          // label默认蓝框白底左上角显示,样式className为:amap-marker-label
          const siteText = new AMap.Text({
            offset: new AMap.Pixel(0, -20),  //设置文本标注偏移量
            text: item[spotNameStr],
            zIndex: 52,
            position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
            map: mapObj
          })
          siteText[customIdKey] = item
          // siteText.on('click', clickHandler1) // 给 siteText 绑定带上 InfoWindow 显示事件
          siteText.setMap(mapObj)
          siteText.hide()
          circleTexts.push(siteText)
          const mouseoverHandler1 = function (e) {
            console.log('text显示')
            _this.showOrHideLabel(e.target[customIdKey], 'mouseover', circleTexts, spotIdKey, spotNameStr, customIdKey);
          }
          const mouseoutHandler1 = function (e) {
            console.log('text隐藏')
            _this.showOrHideLabel(e.target[customIdKey], 'mouseout', circleTexts, spotIdKey, spotNameStr, customIdKey);
          }
          siteMarker.on('mouseover', mouseoverHandler1)
          siteMarker.on('mouseout', mouseoutHandler1)
        })
        // console.log('middleMarkers', middleMarkers)
        return middleMarkers
      },

3.2 然后 鼠标移入移出监听事件内 执行了公共方法 showOrHideLabel() 

/**
       * 标签对象 上绑定的(鼠标移出移入事件)-是否显示 其对应的 text标题信息
       * mapObj 地图对象
       * itemObj 途径站点 带的私货对象
       * mousetype 鼠标移出类型 'mouseover' 'mouseout'
       * markerSet createCircleMarker内的 text对象的 set集合
       * spotIdKey 站点唯一键 字段
       * spotNameStr 站点名称 字段
       * customIdKey maker、text对象上带的自定义私货 所用字段
       * */
      showOrHideLabel(itemObj, mousetype, markerSet, spotIdKey, spotNameStr, customIdKey) {
        // console.log('showOrHideLabel()-itemObj', itemObj, 'mousetype', mousetype, 'markerSet', markerSet, 'spotIdKey', spotIdKey)
        markerSet.forEach(function (element) {
          if (itemObj[spotIdKey] === element[customIdKey][spotIdKey]) {
            if (mousetype === 'mouseover') {
              element.show()
            } else if (mousetype === 'mouseout') {
              element.hide()
            }
          }
        })
      },

至此本文主要实现功能  批量maker上各带鼠标监听事件,实现各自对应text标签显示与隐藏功能实现;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

vue高德多条路线规划+带途径节点多组多个maker + maker批量带各自鼠标移入移出监听事件(对应的text标签显示与隐藏)+各路线颜色区别(版本三) 的相关文章

  • 当指定为对象属性时,IIFE 如何影响其中的此关键字

    var a name Rhona check function return this name console log a check This returns 一个空字符串我希望它返回 Rhona 它没有给出 undefined 或 n
  • 我可以在为服务器提供 API 的同时提供静态文件吗?

    所以我对网络开发还很陌生 现在我和我更加面向网络的朋友开始了一个项目 他向我扔了各种各样的框架 我们正在做 Vuejs jade stylus 和 jeet 对于新手来说 这当然非常令人困惑 因为没有 Vuejs 示例使用 jade 没有
  • Javascript - 事件属性的浏览器命名约定让我感到困惑

    我一直想知道为什么不同浏览器的 JavaScript 中事件的 target sourceElement 的属性名称存在差异 event srcElement in Internet Explorer event target in mos
  • 如何检测访问者使用的是HTTP/2还是SPDY?

    我正在寻找一个可以检测访问者的浏览器是否启用了 SPDY 或 HTTP 2 的脚本 就像是this https www ist http2 aktiviert de 理论上 一次nextHopProtocol降落在资源计时 https w3
  • 在 Foundation 中动态设置 Sass 变量

    如何在 Foundation 中动态设置 Sass 变量 根据他们的文档 http foundation zurb com docs components tables html 您可以借助一些 Sass 变量来自定义表格 settings
  • 在 Google Cloud 中设置网站? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我完全迷失在这之中 我习惯于使用带有 cpanel 的简单 Web 主机来制作网站 只需使用 filezilla 登录并上传我的 ht
  • 如何通过 HTML 输入标签获取文件的引用? (角度2)

    我想在 Firebase 中上传图片 但要做到这一点 我必须先获取文件 例如 如何通过 HTML 获取我的计算机的图像 我正在尝试这样做 但我不知道这样做的回报是什么 帮帮我吧伙计们
  • 将网页中的表格导入 Excel

    我只有中高级的Excel水平和中级的VBA与Excel背景 我想要做的是从链接中显示的网页导入表格 http www admission unmsm edu pe res20130914 A 011 0 html http www admi
  • 如何在 Laravel 7.x 中从控制器返回视图时传递 cookie?

    在 laravel 7 x 中 有什么方法可以在返回视图时将 cookie 传递给客户端吗 类似于 return view welcome gt cookie name value min 嗯 我做了一些研究 发现有一些方法 我熟悉的两个是
  • IIS 7.5:对网站的初始请求永远不会加载

    当我第一次浏览我的网站时 互联网不断旋转 加载 如果我两秒钟后尝试再次加载它 一切都会正常 就好像它 睡着了 一样 我想这一定和 回收 有关 我已将 空闲超时 设置为 0 将回收 定期时间间隔 设置为 0 在浏览我的网站之前 我查看了 工作
  • 尝试访问我的网站时出现内部服务器错误

    我收到这个错误 内部服务器错误 服务器遇到内部错误或配置错误 无法完成您的请求 请联系服务器管理员 电子邮件受保护 cdn cgi l email protection和 告知他们错误发生的时间以及您可能会发生的任何事情 所做的事情可能导致
  • WebUSB 和 RFID 读取器

    我想知道是否有人有让 RFID 读取器通过 WebUSB 工作的经验 我使用的阅读器是https www parallax com product 28340 https www parallax com product 28340 根据我
  • asp.NET 2.0网站无法访问App_Code中的类

    将我的网站部署到服务器后 我在访问课程时遇到问题 请注意 这是一个网络Site不是网络应用 错误是 编译器错误消息 CS0246 找不到类型或命名空间名称 Order 是否缺少 using 指令或程序集引用 版本信息 Microsoft N
  • 为什么使用HTTP协议时需要指定端口号?

    即使我们使用HTTP协议 为什么还需要用IP地址指定端口号 例如 http xyz 8080 这到底是什么意思 我们已经知道 在使用 HTTP 时 请求将在端口 80 上提供服务 那么为什么我们要显式指定端口呢 HTTP 的默认端口为 80
  • Java selenium - 如何在 TimeoutException 之后正确刷新网页?

    ChromeOptions options new ChromeOptions options addExtensions new File extension 6 2 5 0 crx ZenMate options addExtensio
  • Firebase Auth - 最近登录多长时间

    我有一个个人资料选项卡 用户可以在其中按编辑并编辑他们的个人资料 我只想在必要时才需要他们的密码 所以想知道用户登录的时间是多少毫秒 这使得它不是最近登录 其中firebase会抛出错误 auth requires recent login
  • 烧瓶 - 404 未找到

    我是烧瓶开发的新手 这是我在烧瓶中的第一个程序 但它向我显示了这个错误 在服务器上找不到请求的 URL 如果您输入了网址 请手动检查拼写并重试 这是我的代码 from flask import Flask app Flask name ap
  • 在脚本标签内工作的角度表达式

    如何在脚本标签内使用角度表达式 我对此很陌生并且需要帮助 这是我的 java 脚本代码的示例
  • 如何防止桌面浏览器(Chrome、Safari)缩放网页

    我尝试使用以下元视图端口标记来防止浏览器缩放 但这不起作用 我知道这是可能的 因为我的缩放在此网站上被阻止 未来主义 xyz http futurism xyz 该网站的视口标签是这样的
  • IIS 8 HTTPS/需要 SSL 导致超时错误

    尝试通过 IIS 8 通过 SSL 发布网站 但出现超时错误 任何帮助表示赞赏 采取的步骤 已验证该网站可以通过 HTTP 访问 http xxx xxx xxx xxx有效 此时使用 IP 地址 如果重要的话 IIS gt 服务器证书 g

随机推荐