高德地图路径规划


项目开始使用的是百度地图,因为某些原因,就改为了高德地图(只有路径规划使用高德地图),所以有坐标转换,如果只使用高德地图,请忽略!

一、要实现的效果

包含驾车、公交、骑行、步行多种交通方式,如图所示:
在这里插入图片描述
在这里插入图片描述

二、index.html引入js

<script src="//webapi.amap.com/maps?v=1.4.15&key=你自己申请的key&plugin=AMap.Scale,AMap.ToolBar,AMap.OverView,AMap.Autocomplete,AMap.Size,AMap.Pixel"></script>

三、template代码

<template>
  <div style="position:relative" :style="{ height: windowHeight-58 + 'px' }">
    <div class="floatDiv">
      <div class="searchWrap">
        <!--输入框-->
        <el-form ref="pathForm" :model="formData" :rules="rules">
          <el-form-item prop="travelMode" style="margin-bottom:0px;">
            <el-radio-group v-model="formData.travelMode" @change="travelModeChange" size="medium">
              <el-radio-button :label="1">
                <svg-icon icon-class="driving"/>&nbsp;驾车
              </el-radio-button>
              <el-radio-button :label="2">
                <svg-icon icon-class="transfer"/>&nbsp;公交
              </el-radio-button>
              <el-radio-button :label="3">
                <svg-icon icon-class="riding"/>&nbsp;骑行
              </el-radio-button>
              <el-radio-button :label="4">
                <svg-icon icon-class="walking"/>&nbsp;步行
              </el-radio-button>
            </el-radio-group>
            <i style="font-size:18px;position:relative;top:5px;cursor: pointer" @click="drop"
               :class="dropShow?'el-icon-arrow-up':'el-icon-arrow-down'"></i>
          </el-form-item>
          <div style="height:4px"></div>
          <div class="p20" v-if="dropShow">
            <div class="change" @click="exchange"></div>
            <div class="road">
              <el-form-item prop="startKeyword">
                <div class="searchInputWrap">
                  <el-input id="startKeyword" class="text" placeholder="请输入起点" v-model="formData.startKeyword"  ></el-input>
                  <i style="font-size:18px;cursor: pointer" class="el-icon-circle-plus-outline" @click="addDomain"
                     v-if="formData.travelMode == 1 && formData.domains.length < 6"></i>
                </div>
              </el-form-item>
              <el-form-item v-for="(domain, index) in formData.domains"
                            :key="domain.key"
                            :prop="'domains.' + index + '.value'"
                            :rules="{required: true, message: '请输入途经点', trigger: 'blur'}"
                            v-if="formData.travelMode == 1"
              >
                <div class="searchInputWrap">
                  <el-input v-model="domain.value" :id="'middleKeyWord' + index" class="text" placeholder="请输入途经点" clearable ></el-input>
                  <i style="font-size:18px;cursor: pointer" class="el-icon-remove-outline" @click.prevent="removeDomain(domain)"></i>
                </div>
              </el-form-item>
              <el-form-item prop="endKeyword">
                <div class="searchInputWrap">
                  <el-input id="endKeyword" class="textEnd" placeholder="请输入终点" v-model="formData.endKeyword" clearable></el-input>
                </div>
              </el-form-item>
            </div>

          </div>
          <el-form-item v-if="dropShow">
            <div class="searchBtn">
              <div></div>
              <el-button type="primary" @click="search">{{formData.travelMode == 1?'驾车去':formData.travelMode ==
                2?'坐公交':formData.travelMode == 3?'骑车去':'走路去'}}
              </el-button>
            </div>
            <!--            <el-button type="danger" @click="reset">重置</el-button>-->
          </el-form-item>
        </el-form>
      </div>
      <!--导航结果-->
      <el-scrollbar ref="scroll" style="height:500px;" v-if="panelShow">
        <div id="panel" ref="panel"></div>
      </el-scrollbar>
    </div>
    <!--地图-->
    <div id="container" v-loading="loading"></div>
  </div>
</template>

四、script代码

<script>
  import $ from 'jquery'
  import * as  outlets from '@/api/website/outlets'
  import { getFtpUrl, getUploadUrl } from '@/utils/base'
  export default {
    name: "index",
    data() {
      return {
        loading: false,
        imgs: require("@/assets/map/img/no_img.png"),
        clickInfo: null,  //单击描点数据
        formData: {
          startKeyword: '',  //起点
          endKeyword: '',//终点
          travelMode: 1,//出行方式
          domains: [],
        },
        dropShow: true,
        panelShow: false,
        localSearch: null,//自动搜索
        map: null,
        outletsList: [],//查询网点的数据
        windowHeight: document.documentElement.clientHeight,   //实时屏幕高度

        //路线规划
        driving: null,
        walking: null,
        transfer: null,
        riding: null,
        rules: {
          travelMode: [
            {required: true, message: '请选择出行方式', trigger: 'change'},
          ],
          startKeyword: [
            {required: true, message: '请输入起点', trigger: 'blur'},
          ],
          endKeyword: [
            {required: true, message: '请输入终点', trigger: 'blur'},
          ],
        }
      }
    },
    mounted() {
      this.init();
      this.queryOutlets();
      var that = this;
      // <把window.onresize事件挂在到mounted函数上
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight - 50;
          that.windowHeight = window.fullHeight;  // 高
        })()
      };
    },
    watch: {
      windowHeight(val) {
      },
    },
    created() {
      //设置事件
      let _this = this;
      window.setStart = _this.setStart;
      window.setMiddle = _this.setMiddle;
      window.setEnd = _this.setEnd;
    },
    methods: {
      //开始结束地址交换
      exchange() {
        var temp = "";
        temp = this.formData.startKeyword;
        this.formData.startKeyword = this.formData.endKeyword;
        this.formData.endKeyword = temp;
      },

      //折叠
      drop() {
        this.dropShow = !this.dropShow
        //关闭前保存结果 打开的时候将结果回显
        if (this.panelShow == true) {
          this.results = this.$refs.panel;
          this.panelShow = !this.panelShow
        } else {
          this.panelShow = !this.panelShow
          this.$nextTick(() => {
            $("#panel").html(this.results);
          });
        }
      },

      //切换出行方式
      travelModeChange(){
        this.dropShow = true;
        this.formData.domains = [];
        if (this.formData.startKeyword != '' && this.formData.endKeyword != '') {
          this.search();
        }
      },

      //查询全部网点
      queryOutlets() {
        var that = this;
        var data = [];
        var style = [{
          url: require('@/assets/map/icon/bank.png'),
          anchor: new AMap.Pixel(14, 14),
          size: new AMap.Size(28, 28),
          // zIndex: 每种样式图标的叠加顺序,数字越大越靠前
          zIndex: 100,
        }, {
          url: require('@/assets/map/icon/post.png'),
          anchor: new AMap.Pixel(14, 14),
          size: new AMap.Size(28, 28),
          zIndex: 100,
        }, {
          url: require('@/assets/map/icon/postSaving.png'),
          anchor: new AMap.Pixel(14, 14),
          size: new AMap.Size(28, 28),
          zIndex: 100,
        }, {
          url: require('@/assets/map/icon/saving.png'),
          anchor: new AMap.Pixel(14, 14),
          size: new AMap.Size(28, 28),
          zIndex: 100,
        }, {
          url: require('@/assets/map/icon/investment.png'),
          anchor: new AMap.Pixel(14, 14),
          size: new AMap.Size(28, 28),
          zIndex: 100,
        }];

        var massMarks = new AMap.MassMarks(null, {
          zIndex: 100,  // 海量点图层叠加的顺序
          zooms: [3, 19],  // 在指定地图缩放级别范围内展示海量点图层
          style: style  // 设置样式对象
        });

        //获取全部网点信息
        outlets.getListBySearch({}).then(async response => {
          that.outletsList = response.data
          var firstArr = [];
          var secondArr = [];
          var thirdArr = [];
          var fourth = [];
          var fifthArr = [];
          //遍历添加数据
          for (let i = 0; i < that.outletsList.length; i++) {
            var obj = {
              lnglat: [that.outletsList[i].lng, that.outletsList[i].lat], //点标记位置
              name: that.outletsList[i].outletsName,
              id: i,
              style: 0
            };

            if (that.outletsList[i].type == 1) {
              obj.style = 0
            } else if (that.outletsList[i].type == 2) {
              if (that.outletsList[i].outletsType == 1) {
                obj.style = 1
              } else if (that.outletsList[i].outletsType == 2) {
                obj.style = 2
              } else {
                obj.style = 3
              }
            } else {
              obj.style = 4
            }


            if (i < 1000) {
              firstArr.push(obj.lnglat);
            } else if (i < 2000) {
              secondArr.push(obj.lnglat);
            } else if (i < 3000) {
              thirdArr.push(obj.lnglat);
            } else if (i < 4000) {
              fourth.push(obj.lnglat);
            } else {
              fifthArr.push(obj.lnglat);
            }
            data.push(obj)
          }

          var resultArr = [];
          if (firstArr.length > 0) {
            let res = await that.convertBMapToAMap(firstArr)
            resultArr.push.apply(resultArr, res);
          }
          if (secondArr.length > 0) {
            let res = await that.convertBMapToAMap(secondArr)
            resultArr.push.apply(resultArr, res);
          }
          if (thirdArr.length > 0) {
            let res = await that.convertBMapToAMap(thirdArr)
            resultArr.push.apply(resultArr, res);
          }
          if (fourth.length > 0) {
            let res = await that.convertBMapToAMap(fourth)
            resultArr.push.apply(resultArr, res);
          }
          if (fifthArr.length > 0) {
            let res = await that.convertBMapToAMap(fifthArr)
            resultArr.push.apply(resultArr, res);
          }

          //将百度坐标改为高德坐标
          for (let i = 0; i < resultArr.length; i++) {
            data[i].lnglat = resultArr[i]
          }

          massMarks.setData(data);

          //信息窗体的单击事件
          massMarks.on('click', function (e) {
            that.showInfoWindow(e);
          });

          // 将海量点添加至地图实例
          massMarks.setMap(that.map);

          //that.loading = false
        })
      },

      //百度坐标转高德坐标
      convertBMapToAMap(lnglat) {
        return new Promise(r => {
          AMap.convertFrom(lnglat, "baidu", function (status, result) {
            if (result.info === 'ok') {
              r(result.locations)
            }
          })
        })
      },

      //显示信息窗体
      async showInfoWindow(e) {
        var that = this;
        that.clickInfo = e;
        //网点类型
        var type = "";
        var content = [];   //内容

        //设置网点类型和图片
        if (that.outletsList[e.data.id].type == 1) {
          type = "**网点"
          content.push("<img src='" + that.imgs + "' style='object-fit:cover;margin:0px 20px 0 0;float:left;width:216px;height:173px;'>");
        } else if (that.outletsList[e.data.id].type == 2) {
          if (that.outletsList[e.data.id].outletsType == 1) {
            type = "**网点"
          } else if (that.outletsList[e.data.id].outletsType == 1) {
            type = "**网点"
          } else {
            type = "**网点"
          }
          if (JSON.parse(that.outletsList[e.data.id].streetPhoto).length > 0) {
            var src = getFtpUrl() + JSON.parse(that.outletsList[e.data.id].streetPhoto)[0].path;
            content.push("<img src='" + src + "' style='object-fit:cover;margin:0px 20px 0 0;float:left;width:216px;height:173px;'></img>");
          } else {
            content.push("<img src='" + that.imgs + "' style='object-fit:cover;margin:0px 20px 0 0;float:left;width:216px;height:173px;'>");
          }
        } else {
          type = "**部"
          if (JSON.parse(that.outletsList[e.data.id].location).length > 0) {
            var src = getFtpUrl() + JSON.parse(that.outletsList[e.data.id].location)[0].path;
            content.push("<img src='" + src + "' style='object-fit:cover;margin:0px 20px 0 0;float:left;width:216px;height:173px;'></img>");
          } else {
            content.push("<img src='" + that.imgs + "'  style='object-fit:cover;margin:0px 20px 0 0;float:left;width:216px;height:173px;'>");
          }
        }

        //标题
        var title = '<span style="font-size:14px;font-weight: bold;color:#02504D">网点信息弹窗</span>';
        content.push("<div><div style='font-size:14px;line-height:30px;font-weight:bold;color:#282828'>" + e.data.name + "</div>");
        content.push("<div style='font-size:14px;line-height:30px;color:#666;'>类型:" + type + "</div>");
        content.push("<div style='font-size:14px;line-height:24px;color:#666;'>地址:" + that.outletsList[e.data.id].address + "</div>");
        content.push("<input type='button' class='btn' value='设为起点' οnclick='setStart()' ref='btnStart' style='cursor:pointer;outline:none; margin:10px 20px 0px 0;border-radius:4px;width:80px;height:26px;background:#409EFF;border:0;color:#fff;float:left;'/>");

        //只有驾车才有途经点 并且途经点最多有6个
        if (that.formData.travelMode == 1 && that.formData.domains.length < 6) {
          content.push("<input type='button' class='btn' value='设为途经点' οnclick='setMiddle()' ref='btnMiddle' style='cursor:pointer;outline:none; margin:10px 20px 0px 0;border-radius:4px;width:90px;height:26px;background:#409EFF;border:0;color:#fff;float:left;'/>");
        }
        content.push("<input type='button' class='btn' value='设为终点' οnclick='setEnd()' ref='btnEnd' style='cursor:pointer;outline:none; margin:10px 20px 0px 0;border-radius:4px;width:80px;height:26px;background:#409EFF;border:0;color:#fff;float:left;'/></div>");

        var cont = await that.createInfoWindow(title, content.join(" "));//调用创建信息窗体的方法--信息窗体的内容

        //构建自定义信息窗体
        var infoWindow = new AMap.InfoWindow({
          anchor: 'bottom-center',
          content: cont,
        });
        infoWindow.open(that.map, [e.data.lnglat.lng, e.data.lnglat.lat]);
      },

      //设为起点
      setStart(){
        var that = this;
        var geocoder = new AMap.Geocoder({
          city: "河南", //城市设为河南,默认:“全国”
          radius: 1000 //范围,默认:500
        });
        var arr = [that.clickInfo.data.lnglat.lng, that.clickInfo.data.lnglat.lat];
        geocoder.getAddress(arr, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            var address = result.regeocode.formattedAddress;
            that.formData.startKeyword = address
          } else {
            console.log('根据经纬度查询地址失败')
          }
        });
      },

      //设为途经点
      setMiddle(){
        var that = this;
        var geocoder = new AMap.Geocoder({
          city: "河南", //城市设为河南,默认:“全国”
          radius: 1000 //范围,默认:500
        });
        var arr = [that.clickInfo.data.lnglat.lng, that.clickInfo.data.lnglat.lat];
        geocoder.getAddress(arr, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            var address = result.regeocode.formattedAddress;
            if (that.formData.domains.length < 6){
              that.formData.domains.push({value: address});
            }else {
              that.$message.error('最多只能添加6个途经点')
            }
          } else {
            console.log('根据经纬度查询地址失败')
          }
        });
      },

      //设为终点
      setEnd(){
        var that = this;
        var geocoder = new AMap.Geocoder({
          city: "河南", //城市设为河南,默认:“全国”
          radius: 1000 //范围,默认:500
        });
        var arr = [that.clickInfo.data.lnglat.lng, that.clickInfo.data.lnglat.lat];
        geocoder.getAddress(arr, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            var address = result.regeocode.formattedAddress;
            that.formData.endKeyword = address;
          } else {
            console.log('根据经纬度查询地址失败')
          }
        });
      },

      //构建自定义信息窗体
      createInfoWindow(title, content) {
        var that = this
        return new Promise(r => {
          //info 为 信息窗体
          var info = document.createElement("div");
          info.className = "info";

          //可以通过下面的方式修改自定义窗体的宽高
          info.style.width = "479px";
          info.style.height = "250px";
          // 定义顶部标题
          var top = document.createElement("div");
          var titleD = document.createElement("div");
          // var closeX = document.createElement("img");
           top.className = "info-top";
           titleD.innerHTML = title;

          top.appendChild(titleD);
          info.appendChild(top);   //信息窗体增加顶部的div

          // 定义中部内容
          var middle = document.createElement("div");
          middle.className = "info-middle";
          middle.innerHTML = content;
          info.appendChild(middle);  //信息窗体增加中部的div

          // 定义底部内容
          var bottom = document.createElement("div");
          bottom.className = "info-bottom";
          bottom.style.position = 'relative';
          bottom.style.top = '0px';
          bottom.style.margin = '0 auto';
          info.appendChild(bottom);  //信息窗体增加底部的div
          r(info)
        });
      },

      //关闭信息窗体
      /*closeInfoWindow() {
        this.map.clearInfoWindow();
      },*/
      //删除动态表单
      removeDomain(item) {
        var index = this.formData.domains.indexOf(item)
        if (index !== -1) {
          this.formData.domains.splice(index, 1)
        }
      },
      //添加动态表单
      addDomain() {
        this.formData.domains.push({
          value: '',
        });
        this.$nextTick(() => {
          var middleKeyWord = new AMap.Autocomplete({
            input: "middleKeyWord" + (this.formData.domains.length - 1)
          });
        });
      },

      //驾车导航
      async checkDriving() {
        var that = this;
        //var driving;
        that.map.plugin('AMap.Driving', function () {
          that.driving = new AMap.Driving({
            map: that.map,
            panel: "panel"
          });
        });

        //起点和终点
        var start = await that.geoCode(that.formData.startKeyword);
        var end = await that.geoCode(that.formData.endKeyword);

        if (start == "no_data"){
          this.$message.error('请输入详细的起点')
          return;
        }
        if (end == "no_data"){
          this.$message.error('请输入详细的终点')
          return;
        }

        //判断途经点
        var arr = [];
        if (that.formData.domains.length > 0) {
          for (let i = 0; i < that.formData.domains.length; i++) {
            var result = await that.geoCode(that.formData.domains[i].value);
            if (result == "no_data") {
              this.$message.error('请输入详细的途经点')
              return;
            }
            arr.push(new AMap.LngLat(result.lng, result.lat))
          }
        }

        that.driving.search(new AMap.LngLat(start.lng, start.lat), new AMap.LngLat(end.lng, end.lat), {
          waypoints: arr
        }, function (status, result) {
          // result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            //console.log('绘制驾车路线完成')
          } else {
            console.log('获取驾车数据失败:' + result)
          }
        });
      },

      //根据地址查询坐标
      geoCode(address) {
        var that = this;
        var geocoder;
        return new Promise(r => {
          that.map.plugin('AMap.Geocoder', function () {
            geocoder = new AMap.Geocoder({
              map: that.map,
              panel: "panel"
            });
          });
          geocoder.getLocation(address, function (status, result) {
            if (status === 'complete' && result.geocodes.length) {
              var lnglat = result.geocodes[0].location
              r(lnglat);
            }else {
              //console.log('根据地址查询位置失败');
              r(status);
            }
          });
        });
      },
      //步行导航
      checkWalking() {
        var that = this;
        //var walking;
        that.map.plugin('AMap.Walking', function () {
          that.walking = new AMap.Walking({
            map: that.map,
            panel: "panel"
          });
        });
        that.walking.search([
          {keyword: that.formData.startKeyword, city: '河南'},
          {keyword: that.formData.endKeyword, city: '河南'}
        ], function (status, result) {
          // result即是对应的步行路线数据信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_WalkingResult
          if (status === 'complete') {
            //console.log('绘制步行路线完成')
          } else if (result == "OVER_DIRECTION_RANGE") {
            that.$message.error('起点终点距离过长')
          } else {
            console.log('步行路线数据查询失败')
          }
        });
      },
      //公交
      checkTransit() {
        var that = this;
        //var transfer;
        that.map.plugin('AMap.Transfer', function () {
          that.transfer = new AMap.Transfer({
            map: that.map,
            panel: "panel",
            //公交换乘策略
            policy: AMap.TransferPolicy.LEAST_TIME
          });
        });
        //根据起、终点名称查询公交换乘路线
        that.transfer.search([
          {keyword: that.formData.startKeyword, city: '河南'},
          {keyword: that.formData.endKeyword, city: '河南'}
          //第一个元素city缺省时取transOptions的city属性
          //第二个元素city缺省时取transOptions的cityd属性
        ], function (status, result) {
          // result即是对应的公交路线数据信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferResult
          if (status === 'complete') {
            //console.log('绘制公交路线完成')
          } else if (result == "OVER_DIRECTION_RANGE") {
            that.$message.error('起点终点距离过长')
          } else {
            console.log(result.info || '公交路线数据查询失败' + result)
          }
        });
      },
      //骑行
      checkRiding() {
        var that = this;
        //var riding;
        that.map.plugin('AMap.Riding', function () {
          that.riding = new AMap.Riding({
            map: that.map,
            panel: "panel"
          });
        });
        that.riding.search([
          {keyword: that.formData.startKeyword, city: '河南'},
          {keyword: that.formData.endKeyword, city: '河南'}
        ], function (status, result) {
          // result即是对应的骑行路线数据信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
          if (status === 'complete') {
            //console.log('绘制骑行路线完成')
          } else if (result == "OVER_DIRECTION_RANGE") {
            that.$message.error('起点终点距离过长')
          } else {
            console.log('骑行路线数据查询失败' + result)
          }
        });
      },

      //搜索按钮
      search() {
        var that = this;
        this.$refs.pathForm.validate((valid) => {
          if (valid) {
            if (this.formData.startKeyword == this.formData.endKeyword){
              that.$message.error('起点不能与终点相同')
              return;
            }
            delete that.formData.label;
            // 清除地图上所有添加的覆盖物
            $("#panel").html("");

            //会把描边也清除掉
            //that.map.clearMap();

            //清空规划路线
            if (that.driving!=null){
              that.driving.clear();
            }
            if (that.walking!=null){
              that.walking.clear();
            }
            if (that.transfer!=null){
              that.transfer.clear();
            }
            if (that.riding!=null){
              that.riding.clear();
            }

            if (this.formData.travelMode == 1) {
              that.checkDriving();
            } else if (this.formData.travelMode == 2) {
              that.checkTransit();
            } else if (this.formData.travelMode == 3) {
              that.checkRiding();
            } else {
              that.checkWalking();
            }
            that.panelShow = true;
          }
        })
      },

      //初始化地图
      init() {
        var that = this;
        that.map = new AMap.Map('container', {
          resizeEnable: true, //是否监控地图容器尺寸变化
          zoom: 10, //初始化地图层级
          keyboardEnable: true,//地图是否可通过键盘控制
          dragEnable: true,//地图是否可通过鼠标拖拽平移
          center: [113.657791, 34.745757], //初始化地图中心点
        });

        that.map.addControl(new AMap.Scale());//比例尺
        that.map.addControl(new AMap.ToolBar({position: 'RT'}));//缩放

        //设置地图的显示样式
        that.map.setMapStyle('amap://styles/261b68dd55ea75daa669fbe46111e332');

        //定位
        AMap.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:5s
            buttonPosition: 'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: false,   //定位成功后是否自动调整地图视野到定位点

          });
          that.map.addControl(geolocation);
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              //设置地图中心点
              //that.map.setCenter([result.position.lng, result.position.lat]);
              //同时设置地图层级与中心点
              that.map.setZoomAndCenter(11, [result.position.lng, result.position.lat]);
            } else {
              console.log("定位失败")
            }
          });
        });

        //middleKeyWord
        //输入提示
        var startKeyword = new AMap.Autocomplete({
          input: "startKeyword"
        });
        var endKeyword = new AMap.Autocomplete({
          input: "endKeyword"
        });

        //获取边界坐标点
        AMap.plugin('AMap.DistrictSearch', () => {
          var districtSearch = new AMap.DistrictSearch({
            // 关键字对应的行政区级别,共有5种级别
            level: 'province',
            //  是否显示下级行政区级数,1表示返回下一级行政区
            subdistrict: 0,
            // 返回行政区边界坐标点
            extensions: 'all',
          })

          // 搜索所有省/直辖市信息
          districtSearch.search('河南', (status, result) => {
            // 查询成功时,result即为对应的行政区信息
            that.handlePolygon(result)
          })
        })
      },

      //绘制河南省边界线
      handlePolygon(result) {
        var that = this;
        let bounds = result.districtList[0].boundaries
        if (bounds) {
          for (let i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            let polygon = new AMap.Polygon({
              map: that.map,    // 指定地图对象
              strokeWeight: 2,    // 轮廓线宽度
              path: bounds[i],     //轮廓线的节点坐标数组
              fillOpacity: 0.01,     //透明度
              fillColor: '#FFFFFF',     //填充颜色
              strokeColor: '#3a7a77',    //线条颜色
            })
            // polygon.on('click', (e) => {
            //   // 点击绘制的区域时执行其他交互
            // ......
            // })
          }
          // 地图自适应
          //that.map.setFitView()
        }
      }
    }
  }
</script>

五、style

<style scoped>
  /deep/ .amap-info-content {
    padding-left: 20px;
    border-radius: 10px;
  }

  /deep/ .amap-info-close {
    top: 12px;
  }

  /deep/ .info-middle {
    display: flex;
    background: #fff;
    padding-top: 20px;
  }
  /*地图默认*/
  #container {
    width: 100%;
    height: 100%;
  }

  #panel {
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    width: 368px;
  }

  #panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }

  #panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
  }

  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  /*搜索*/
  .floatDiv {
    position: absolute;
    z-index: 3;
    left: 20px;
    top: 20px;
    width: 368px;
    overflow: hidden;
  }

  .searchWrap {
    background: #fff;
    margin-bottom: 10px;
    box-shadow: 0 2px 2px rgba(0, 0, 0, .1);
  }

  .p20 {
    padding: 10px 20px 10px 0;
    display: flex;
    align-items: center;
  }
  .change{
    width:40px;
    height:70px;
    background: url("../../../assets/map/mapIcon2.png") 10px center no-repeat;
    cursor: pointer;
    margin-bottom:18px;
  }
  .road{
    flex:1;
  }
  .searchInputWrap {
    border-bottom: solid 1px #ededed;
    display: flex;
    align-items: center;
  }

  .text {
    width: 290px;
    border: 0;
  }

  .text /deep/ .el-input__inner {
    border: 0;
    font-size: 14px;
    background: url("../../../assets/map/mapIconStart.png") 5px center no-repeat;
    padding-left: 20px;
  }

  .text /deep/ .el-input__suffix i {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.65);
  }

  .textEnd {
    width: 290px;
    border: 0;
  }

  .textEnd /deep/ .el-input__inner {
    border: 0;
    font-size: 14px;
    background: url("../../../assets/map/mapIconEnd.png") 5px center no-repeat;
    padding-left: 20px;
  }

  .textEnd /deep/ .el-input__suffix i {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.65);
  }

  /deep/ .el-form-item__error {
    padding: 5px 0 0 20px;
  }

  .searchBtn {
    display: flex;
    justify-content: space-between;
    text-align: right;
    padding: 10px 20px;
  }

  /deep/ .el-radio-group {
    position: relative;
    left: -1px;
  }

  /deep/ .el-radio-button__inner {
    border: 1px solid #409EFF;
    border-width: 0 0 1px 0;
    width: 83px;
  }

  /deep/ .el-radio-button:first-child .el-radio-button__inner {
    border-radius: 0;
  }

  /deep/ .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 0;
  }

  /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #fff;
    color: #409EFF;
    box-shadow: 0 0 0 #409EFF;
    position: relative;
    border-radius: 0;
  }

  /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner:after {
    content: '';
    display: block;
    width: 8px;
    height: 8px;
    background: #fff;
    border-right: 1px solid #409EFF;
    border-top: 1px solid #409EFF;
    -webkit-transform: rotate(-45deg); /*箭头方向可以自由切换角度*/
    transform: rotate(-45deg);
    position: absolute;
    bottom: -4px;
    left: 40px;
  }
</style>

六、项目中用到的图标

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值