高德行政区查询-综合省市县三级选择跳转

一、需求:

需要使用高德地图进行省市县的一个选择,每选择一次就在地图上对选择的省市县进行定位并画出该区域的范围。

最终效果

在这里插入图片描述

二、准备工作

高德的API的key:两种
在这里插入图片描述

三、完整页面代码

综合的是这两篇中的内容(不了解的可以先去看这两篇):

高德行政区划查询(vue实现)

省市县选择三级联动(使用高德API实现)

将页面中的key替换为自己申请的两种key

<template>
  <div>
    <div id="container" ref="amap"></div>


    <div class="input-card-container">

      <el-cascader
        filterable
        placeholder="请选择"
        ref="addPoint"
        :props="cityProps"
        :options="cityOptions"
        clearable
        @active-item-change="handleActiveItemChange"
        @change="handleChange"
        v-model="selectedOptions"
        class="input-card"
      ></el-cascader>

    </div>


  </div>


</template>

<script>
  window._AMapSecurityConfig = {
    securityJsCode: "密钥",
  };
  import AMapLoader from '@amap/amap-jsapi-loader';
  import axios from "axios";
  export default {
    name: "Class",
    data() {
      return {
        level:'district',
        district:null,
        polygon:null,
        keyWord:'朝阳区',

        /*获取数据的url key需要自己到高德地图申请*/
        url: 'https://restapi.amap.com/v3/config/district?keywords=&subdistrict=3&extensions=base&key=web服务key',
        /*选项列表*/
        cityOptions: [],
        /*选项列表格式*/
        cityProps: {
          value: 'name',
          label: 'name',
          children: 'districts',
        },
        selectedOptions: null, //选中的数据
      };
    },
    created() {
      this.initAMap();
      this.getCity();

    },
    methods: {

      initAMap() {
        AMapLoader.load({
          key: 'jskey', // 申请好的Web端开发者Key,首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
          plugins: ['AMap.DistrictSearch','AMap.Polygon']  // 需要使用的的插件列表,如比例尺'AMap.Scale'等,如果是地图控件,必须再 map.addControl添加
        })
          .then((AMap) => {
            this.map = new AMap.Map('container', {
              // 设置地图容器id
              //viewMode: '3D', // 默认2d地图模式
              zoom: 12, // 初始化地图级别
              zooms: [5, 30], // 地图缩放范围
              // 可以设置初始化当前位置
              center: [116.397428, 39.90923] // 初始化地图位置
            })
          })
      },
      /* 获取省市区选项 */
      getCity() {
        axios.get(this.url, null).then((res) => {
          console.log(res)
          this.cityOptions = this.getTreeData(
            res.data.districts[0].districts
          )
        })
      },
      /* 递归处理末尾项district为0的空项 */
      getTreeData(data) {
        // 循环遍历返回的数据
        for (var i = 0; i < data.length; i++) {
          if (data[i].districts.length < 1) {
            // districts若为空数组,则将districts设为undefined
            data[i].districts = undefined
          } else {
            // districts若不为空数组,则继续 递归调用 本方法
            this.getTreeData(data[i].districts)
          }
        }
        return data
      },

      handleActiveItemChange(seleted){
        console.log(seleted,"handleActiveItemChange-----")
        this.onSubmit(seleted);
      },

      handleChange(seleted){
        console.log(seleted,"handleChange-----")
        this.onSubmit(seleted);
      },

      /**绘制区域*/
      drawBounds(name) {
        if (!this.district) {
          var opts = {
            subdistrict: 0,
            extensions: 'all',
            level: this.level // 使用数据属性 level
          };
          this.district = new AMap.DistrictSearch(opts);
        }

        if (!this.keyWord) {
          console.warn('名称不能为空');
          return;
        }

        // this.district.setLevel(this.level); // 使用数据属性 level

        this.district.level=this.level;
        console.log(this.district,"district-----------")
        //行政区查询
        this.district.search(name, (status, result) => { // 使用箭头函数保留 this 上下文
          if (this.polygon) {
            this.map.remove(this.polygon); // 使用 this.map
            this.polygon = null;
            //status:complete 表示查询成功,no_data 为查询无结果,error 代表查询错误
            //查询成功时,result 即为对应的行政区信息
          }

          console.log(result,"result---------")
          if (!result || !result.districtList || !result.districtList[0]) {
            console.warn('请正确填写名称或更新其他名称');
            return;
          }

          const bounds = result.districtList[0].boundaries;
          console.log(bounds,"边界信息------")
          if (bounds) {
            for (let i = 0; i < bounds.length; i += 1) {
              bounds[i] = [bounds[i]];
            }

            this.polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds,
              fillOpacity: 0.4,
              fillColor: '#80d8ff',
              strokeColor: '#0091ea'
            });

            this.map.add(this.polygon);
            this.map.setFitView(this.polygon);
          }
        });
      },

      onSubmit(selected){
        //通过长度判断是省市县哪一级
        console.log(selected.length,"onsubmit----")

        if(selected.length==1){//省级
          //取省名称
          var provinceName;
          provinceName=selected[0];
          this.drawBounds(provinceName);
        }
        if(selected.length==2){//市级
          var cityName;
          cityName=selected[1];
          this.drawBounds(cityName);
        }
        if(selected.length==3){//县级
          var countyName;
          countyName=selected[2];
          this.drawBounds(countyName);
        }

      },


    }
  };
</script>

<style scoped lang="scss">
  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 900px;
    position: relative;
  }
  .input-card-container {
    /*position: absolute;*/
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1;
  }
</style>

  • 31
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丿BAIKAL巛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值