Ruta de dibujo del mapa Vue+ Gaode

1. Desarrollo de Vue+Amap


Recientemente, los mapas de proyectos de desarrollo se usan con más frecuencia, como Amap, Baidu map o echars map, y la mayoría de ellos se usan para mostrar rutas, por lo que hoy hablaré sobre el uso de Amap (no el uso completo de Amap).

2. Pasos de uso

Primero, ingresa al sitio web oficial de Amap para registrarte y obtener la clave.

1.Instalación e introducción

El primer método
1. Instalar a través de npm

npm install --save vue-amap

2. Referencia global en main.js

import Amap from "vue-amap"

El segundo tipo se introduce directamente a través de cdn.

<script src="https://webapi.amap.com/maps?v=1.4.15&key=密钥&plugin=AMap.DistrictSearch,AMap.Driving"></script>

Esta introducción debe configurarse en vue.config.js

module.exports = {
    
    
  // 放置静态资源的地方 (js/css/img/font/...)
  assetsDir: 'static',
  configureWebpack: {
    
    
    externals: {
    
    
      'AMap': 'AMap' // 高德地图配置
    }
  },
}

Presenté el mapa de Gaode mediante el segundo método.

Uso de la página:

            <div style="height:100%;width:100%;outline: none!important;" id="amap"></div>
            <div id="panel"></div>
            <div class="radio-group-car">
              <el-radio-group v-model="radio1" @change="changePathHandle(1)">
                <el-radio-button label="1">收费路径</el-radio-button>
                <el-radio-button label="2">稽核路径</el-radio-button>
                <!-- <el-radio-button label="3">全部</el-radio-button> -->
              </el-radio-group>
            </div>
   
<script>
import {
    
     mapGetters } from "vuex";
export default {
    
    
    data() {
    
    
    return {
    
    
      radio1: "",
      switchText: false,
      switchText1: false,
      dialogRadio: "",
      toParams: {
    
    
        lineNameStr: "id",
        spotNameStr: "name",
        pathListNameStr: "list",
      },
      gantryMap:[ 
       {
    
    
          code:"122"
          latitude: "31.825610"
		  longitude: "117.421772"
	      name: "龙塘",
	      list:[
	        {
    
    
	          code:"122"
              latitude: "31.808747"
		      longitude: "117.195950"
		      name: "集贤"
          },
          {
    
    
            code: "121"
		    image: ""
		    latitude: "30.833253"
		    longitude: "117.76409"
		    name: "铜陵"
		    tollIntervalStatus: "2"
		    transTime: null
		    type: 1
          }
	     ]
        },
         {
    
    
          code: "113"
          latitude: "31.825610"
		  longitude: "117.421772"
	      name: "龙塘",
	      list:[
	        {
    
    
	          code: "112"
              latitude: "31.808747"
		 	  longitude: "117.195950"
		 	  tollPlazaCode: "G00403400200501010"
		 	  name: "集贤"
        },
        {
    
    
          code: "111"
		  image: ""
		  latitude: "30.833253"
		  longitude: "117.76409"
		  name: "铜陵"
		  tollIntervalStatus: "2"
		  transTime: null
		  type: 1
        }
	      ]
        },
      ]
    };
  },
  computed: {
    
    
    ...mapGetters(["userInfo"]),
   
  },
  methods: {
    
    
    getCarDetails(value, index) {
    
    
     //我做的是两个路径的,两个路径可以一展示,
     //也可以单独分开展示通过changePathHandle方法,首先获取值,
     //这边值写死了,
     this.drivingDialog(this.gantryMap, 2);
     
    },
    changePathHandle(type) {
    
    
      let arr1 = this.gantryMap;
      this.Driving_objOld.clear();
      if (type == 1) {
    
    
        if (this.radio1 == 1) {
    
    
          arr1 = [this.gantryMap[0]];
          this.radioIndex = 0;
        } else if (this.radio1 == 2) {
    
    
          arr1 = [this.gantryMap[1]];
          this.radioIndex = 1;
        }
        this.drivingDialog(arr1, 2);
      } else {
    
    
        if (this.dialogRadio == 1) {
    
    
          arr1 = [this.gantryMap[0]];
          this.radioIndexDialog = 0;
        } else if (this.dialogRadio == 2) {
    
    
          arr1 = [this.gantryMap[1]];
          this.radioIndexDialog = 1;
        }
        this.drivingDialog(arr1, 1);
      }
    },
    initMap(value) {
    
    
      //基本地图加载
      var map = new AMap.Map("amap", {
    
    
        resizeEnable: true,
        center: [117.17, 31.52], //地图中心点
        zoom: 7, //地图显示的缩放级别
        mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
      });
      this.oldMap = map;
      this.shadeHandle(map);
    },
    shadeHandle(map) {
    
    
      new AMap.DistrictSearch({
    
    
        extensions: "all",
        subdistrict: 0,
      }).search("安徽省", function (status, result) {
    
    
        // 外多边形坐标数组和内多边形坐标数组
        var outer = [
          new AMap.LngLat(-360, 90, true),
          new AMap.LngLat(-360, -90, true),
          new AMap.LngLat(360, -90, true),
          new AMap.LngLat(360, 90, true),
        ];
        var holes = result.districtList[0].boundaries;

        var pathArray = [outer];
        pathArray.push.apply(pathArray, holes);
        var polygon = new AMap.Polygon({
    
    
          pathL: pathArray,
          strokeColor: "#00eeff",
          strokeWeight: 1,
          fillColor: "#71B3ff",
          fillOpacity: 0.5,
        });
        polygon.setPath(pathArray);
        map.add(polygon);
      });
    },
    auditHAndle() {
    
    
      this.getCarDetails()
      this.$nextTick(() => {
    
    
        this.initMap();
        this.handleINdex = 0;
      });
    },
    getMapOpen() {
    
    
      this.dialogMap = true;
      this.$nextTick(() => {
    
    
        const lineData = this.gantryMap;
        var map = new AMap.Map("dialog-amap", {
    
    
          resizeEnable: true,
          center: [117.17, 31.52], //地图中心点
          zoom: 7, //地图显示的缩放级别
          mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        });
        this.oldDialogMap = map;
        this.shadeHandle(map);
        this.dialogRadio = "";
        this.drivingDialog(lineData, 1);
      });
    },
    drivingDialog(lineData, value, type) {
    
    
      const _this = this;
      let map = {
    
    };
      let panel = "";
      let radioIndex = "";
      if (value == 1) {
    
    
        map = this.oldDialogMap;
        panel = "dialog-panel";
        radioIndex = _this.radioIndexDialog;
        type = this.switchText;
      } else {
    
    
        map = this.oldMap;
        panel = "panel";
        radioIndex = _this.radioIndex;
        type = this.switchText1;
      }
      const {
    
     lineNameStr, spotNameStr, pathListNameStr } = _this.toParams;
      const colors = ["#FF4500", "#0000FF", "#FFF5EE", "#FF7F50", "#FF6347"];
      AMap.plugin("AMap.Driving", function () {
    
    
        var Driving_obj = new AMap.Driving({
    
    
          // 驾车路线规划策略,AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          map: map,
          // panel: panel,
          policy: AMap.DrivingPolicy.LEAST_TIME
        });
        _this.Driving_objOld = Driving_obj;
        _this.Driving_objOld.clear(); // 清理
        for (let f = 0; f < lineData.length; f++) {
    
    
          const item_path = lineData[f][pathListNameStr];
          const now_length = item_path.length;
          // 这里  本数据结构 特殊,
          //[起点]是单列在父级数据结构内,不在 路径规划list内
          const nowStartItem = lineData[f];
          const item_start_path = nowStartItem;
          item_start_path.longitude = nowStartItem.longitude;
          item_start_path.latitude = nowStartItem.latitude;
          item_start_path[spotNameStr] = nowStartItem.name;
          const item_end_path = item_path[now_length - 1];
          const now_arr = item_path.slice(0, now_length - 1); 
          // 这里 本数据结构 特殊,
          //[起点]是单列在父级数据结构内,不在 路径规划list内
          const item_way_path = now_arr.map((item) => {
    
    
            return new AMap.LngLat(item.longitude, item.latitude);
          });
          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") {
    
    
                console.log("获取车辆路径规划数据成功");
                if (result.routes && result.routes.length) {
    
    
                  drawRoute(result.routes[0], f);
                }
              } else {
    
    
                console.log("获取车辆路径规划数据失败:" + result);
              }
            }
          );
          function splitArr(ar, size = 1) {
    
    
              let index = 0;
              let res = [];
              while (index < ar.length) {
    
    
                  res.push(ar.slice(index, (index+size)));
                  index += size;
              }
              return res;
          }
          if(now_arr.length>15){
    
    
            const newArr = splitArr(now_arr,15)
            newArr.forEach(el=>{
    
    
              _this.createMarkerNormal(
                lineData[f][lineNameStr],
                el,
                map,
                type
              );
            })
          }else{
    
    
            _this.createMarkerNormal(
            lineData[f][lineNameStr],
            now_arr,
            map,
            type
          );
          }
          _this.createMarkerOne(
            lineData[f][lineNameStr],
            item_start_path,
            "起点",
            map
          );
          _this.createMarkerOne(
            lineData[f][lineNameStr],
            item_end_path,
            "终点",
            map
          );
        }
        // 行驶路线规划
        function drawRoute(route, index) {
    
    
          if (radioIndex != "") {
    
    
            index = radioIndex;
          }
          console.log(colors[index], index);
          const path = _this.parseRouteToPath(route);
          let routeLine_obj = {
    
    };
          // 生成 折线路线
          routeLine_obj = new AMap.Polyline({
    
    
            zIndex: 52,
            path: path,
            isOutline: true,
            outlineColor: "#ffeeee",
            borderWeight: 2,
            strokeWeight: 5,
            strokeColor: colors[index] || "#A52A2A",
            lineJoin: "round",
          });
          routeLine_obj.setMap(map);
        }
      });
    },
    getTextName(type) {
    
    
      if (type == 1) {
    
    
        this.oldMap.clearMap();
      } else {
    
    
        this.oldDialogMap.clearMap();
      }
      this.changePathHandle(type);
    },
    createMarkerNormal(lineName, now_arr, map, type) {
    
    
      // 途径节点 marker(集合)- 此处用了 new AMap.Text 需 版本1.4.2
      const {
    
     lineNameStr, spotNameStr, pathListNameStr } = this.toParams;
      let image = "";
      const middleMarkers = [];
      // -------- 中途 站点-----------
      //因为需求,有不同状态的途径点,所以通过颜色的图片展示,
      //需要将原来的途径点css样式重写,看下面css样式 
      now_arr.forEach((item, index) => {
    
    
        if (item.tollIntervalStatus == 1) {
    
    
          image = require("@/assets/images/mjps.png");
        } else if (
          item.tollIntervalStatus == 2 ||
          item.tollIntervalStatus == 3
        ) {
    
    
          image = require("@/assets/images/mj.png");
        } else if (
          item.tollIntervalStatus == 6 ||
          item.tollIntervalStatus == 5
        ) {
    
    
          image = require("@/assets/images/no.png");
        } else if (item.tollIntervalStatus == 4) {
    
    
          image = require("@/assets/images/ps.png");
        } else {
    
    
          image = require("@/assets/images/nomal.png");
        }
        // 创建一个 Icon
        let siteIcon = {
    
    };
        siteIcon = new AMap.Icon({
    
    
          // 图标尺寸
          size: new AMap.Size(19, 34),
          // 图标的取图地址
          image: image,
          // 图标所用图片大小
          imageSize: new AMap.Size(19, 34),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(0, 0),
        });
        const siteMarker = new AMap.Marker({
    
    
          icon: siteIcon,
          position: new AMap.LngLat(item.longitude, item.latitude),
          // offset: new AMap.Pixel(-12, -32),
          map: map,
        });
        const clickHandler1 = function (e) {
    
    
          console.log(1111)
        };
        siteMarker.on("click", clickHandler1);
        return this.creatTextName(map, siteMarker, item, middleMarkers, type);
      });
    },
    creatTextName(map, siteMarker, item, middleMarkers, type) {
    
    
      const {
    
     lineNameStr, spotNameStr, pathListNameStr } = this.toParams;
      // 给 Text 带上自定义私货
      siteMarker.lisaSiteInfo = item;
      // 监听地图- Text 的 点击事件
      const imgs = []
      const img =  this.changeImgUrl(item.image),
      //途径点上面的marker添加事件显示图片
      infoWindowContent = `
            <div>通行图片</div>
              <img src="${
      
      img}" style="width:300px;heigth:300px" />`;
      const clickHandler1 = function (e) {
    
    
        // log.success("carText模拟触发了地图click事件!");
        console.log(e, "e");
        const siteInfo = e.target.lisaSiteInfo;
        new AMap.InfoWindow({
    
    
          content: infoWindowContent,
        }).open(map, e.lnglat);
      };
      siteMarker.on("click", clickHandler1);
      siteMarker.setMap(map);
      middleMarkers.push(siteMarker);
      //-------siteText-------
      // label默认蓝框白底左上角显示,样式className为:amap-marker-label
      let text = "";
      if (type) {
    
    
        text = item[spotNameStr];
      } else {
    
    
        text = "";
      }
      const siteText = new AMap.Text({
    
    
        offset: new AMap.Pixel(0, -50), //设置文本标注偏移量
        text: text,
        position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
        map: map,
      });
      siteText.lisaSiteInfo = item;
      siteText.on("click", clickHandler1);
      siteText.setMap(map);
      middleMarkers.push(siteText);
      return middleMarkers;
    },
    // 起点 或 终点 marker(单个)
    createMarkerOne(lineName, item, type, map) {
    
    
      const {
    
     lineNameStr, spotNameStr, pathListNameStr } = this.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 = "终点";
      }
      // -------- 站点-----------
      const oneMarker = new AMap.Marker({
    
    
        icon: iconUrl,
        position: new AMap.LngLat(item.longitude, item.latitude),
        offset: new AMap.Pixel(-9, -32),
        map: map,
      });
      // 给 Text 带上自定义私货
      oneMarker.lisaSiteInfo = item;

      oneMarker.setMap(map);
      //-------siteText-------
      // label默认蓝框白底左上角显示,样式className为:amap-marker-label
      const siteText = new AMap.Text({
    
    
        offset: new AMap.Pixel(0, -50), //设置文本标注偏移量
        text: item[spotNameStr],
        position: new AMap.LngLat(item.longitude, item.latitude), // 这里特殊 本数据结构, startLatitude
        map: map,
      });
      siteText.lisaSiteInfo = item;
      siteText.setMap(map);
      return oneMarker;
    },
    getQueryBigDataVehChangeInfo(value){
    
    
      const data = {
    
    
        "mediaType": "2",
        "vehID": value
      }
      this.$get(this.$Url.queryBigDataVehChangeInfo, data).then((res) => {
    
    
        this.queryBigDataVehChangeInfo = res.data || {
    
    };
      })
    },
    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;
    },
  },
  mounted() {
    
    },
  created() {
    
     this.auditHAndle();
  },
};
</script>

<style>
.amap-lib-marker-mid {
    
    
  background: none;
}
</style>

Supongo que te gusta

Origin blog.csdn.net/qq_32881447/article/details/109514423
Recomendado
Clasificación