一、需求:
需要使用高德地图进行省市县的一个选择,每选择一次就在地图上对选择的省市县进行定位并画出该区域的范围。
最终效果:
二、准备工作
高德的API的key:两种
三、完整页面代码
综合的是这两篇中的内容(不了解的可以先去看这两篇):
高德行政区划查询(vue实现)
省市县选择三级联动(使用高德API实现)
将页面中的key替换为自己申请的两种key
<template><div><div id="container" ref="amap"></div><div class="input-card-container"><el-cascaderfilterableplaceholder="请选择"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.15plugins: ['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设为undefineddata[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); // 使用数据属性 levelthis.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.mapthis.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>