Vue3添加高德地图、Vue3添加省市区三级联动

目录

 1.进入高德地图官网    官网地址:高德开放平台 | 高德地图API

2.到这步直接运行代码

3.注意写入你的key 

4.注意更改你所需的初始化地图中心位置

 1-1  Vue3添加省市区三级联动

1-1.1代码

1-1.2省市区都选择 


 

 1.进入高德地图官网    官网地址:高德开放平台 | 高德地图API

# 安装地图命令
npm i @amap/amap-jsapi-loader --save

注册账号 - 认证 - 控制台 - 应用 -我的应用 -添加 key

 

 

 

 

2.到这步直接运行代码

<template>
    <div class="app-container">
        <div style="background-color: #ffffff;">
            <div id="container"></div>
        </div>
    </div>
</template>
 
<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
/*在Vue3中使用时,需要引入Vue3中的shallowRef方法(使用shallowRef进行非深度监听,
因为在Vue3中所使用的Proxy拦截操作会改变JSAPI原生对象,所以此处需要区别Vue2使用方式对地图对象进行非深度监听,
否则会出现问题,建议JSAPI相关对象采用非响应式的普通对象来存储)*/
import { shallowRef } from '@vue/reactivity';
import {ref} from "vue";
 
// const map = shallowRef(null);
const path = ref([]);
const current_position = ref([]);
 
 
function initMap() {
    window._AMapSecurityConfig = {
        securityJsCode: '8e920f73eb2e6880a92ea6662eefc476',
    }
    AMapLoader.load({
        key:"这里写入你的key", // 申请好的Web端开发者Key,首次调用 load 时必填
        version:"2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        // plugins:[''], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    }).then((AMap)=>{
        const map = new AMap.Map("container",{  //设置地图容器id
            viewMode:"3D",    //是否为3D地图模式
            zoom:13,           //初始化地图级别
            center:[113.808299,34.791787], //初始化地图中心点位置
        });
        // 添加插件
        AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye","AMap.Geolocation","AMap.MapType","AMap.MouseTool"], function () {
            //异步同时加载多个插件
            // 添加地图插件
            map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
            map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
            map.addControl(new AMap.HawkEye()); // 显示缩略图
            map.addControl(new AMap.Geolocation()); // 定位当前位置
            map.addControl(new AMap.MapType()); // 实现默认图层与卫星图,实时交通图层之间切换
 
            // 以下是鼠标工具插件
            const mouseTool = new AMap.MouseTool(map);
            // mouseTool.rule();// 用户手动绘制折线图,测量距离
            mouseTool.measureArea(); // 测量面积
        });
        // 单击
        map.on('click',(e) => {
            // lng ==> 经度值  lat => 维度值
            current_position.value = [e.lnglat.lng,e.lnglat.lat];
            path.value.push([e.lnglat.lng,e.lnglat.lat]);
            // addMarker();
            // addPolyLine();
        })
 
 
        // 实例化点标记
        // 第一种(封成函数来触发)
        function addMarker() {
            const marker = new AMap.Marker({
                icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                position: current_position.value, // 这里我们通过上面的点击获取经纬度坐标,实时添加标记
                // 通过设置 offset 来添加偏移量
                offset: new AMap.Pixel(-26, -54),
            });
            marker.setMap(map);
        }
        // 第二种 直接写死 position 的经纬度值
        /*const marker = new AMap.Marker({
            icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            position: [113.808299,34.791787],
            // 通过设置 offset 来添加偏移量
            offset: new AMap.Pixel(-26, -54),
        });
        marker.setMap(map);*/
 
 
        // 折线
        function addPolyLine() {
            const polyline = new AMap.Polyline({
                path: path.value,
                isOutline: true,
                outlineColor: "#ffeeff",
                borderWeight: 1,
                strokeColor: "#3366FF",
                strokeOpacity: 0.6,
                strokeWeight: 5,
                // 折线样式还支持 'dashed'
                strokeStyle: "solid",
                // strokeStyle是dashed时有效
                // strokeDasharray: [10, 5],
                lineJoin: "round",
                lineCap: "round",
                zIndex: 50,
            });
            map.add([polyline]);
        }
 
 
 
    }).catch(e=>{
        console.log(e);
    })
}
 
initMap()
</script>
 
<style>
#container{
    padding:0px;
    margin: 0px;
    width: 100%;
    height: 800px;
}
</style>

3.注意写入你的key 

4.注意更改你所需的初始化地图中心位置

 

 1-1  Vue3添加省市区三级联动

# 安装三省联动代码
npm install element-china-area-data -S
1-1.1代码
<template>
  <div class="areabox" >
    <el-form-item label="省" prop="province" >
      <el-select
        v-model="form.province"
        placeholder="请选择省"
        :style="{ width: `${prop.width}px`, marginRight: `${prop.gap}px` }"
        @change="handleProvinceSelect"
      >
        <el-option v-for="item in regionData" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="市" prop="city" >
      <el-select
        v-model="form.city"
        placeholder="请选择市"
        :disabled="!form.province || cityList.length == 0"
        :style="{ width: `${prop.width}px`, marginRight: `${prop.gap}px` }"
        @change="handleCitySelect"
      >
        <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="区" prop="district">
      <el-select
        v-model="form.district"
        placeholder="请选择区"
        :style="{ width: `${prop.width}px` }"
        :disabled="!form.province || !form.city || districtList.length == 0"
        @change="handleAreaSelect"
      >
        <el-option v-for="item in districtList" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
  </div>
</template>
<script lang="ts" setup>
import { reactive, computed, ComputedRef } from "vue";
import { regionData, codeToText } from "element-china-area-data";

const prop = withDefaults(
  defineProps<{
    gap: string | number; //选择框中间间隙
    width: string | number; //选择框宽度
  }>(),
  {
    gap: "8",
    width: "220",
  }
);
//抛出地址
const emit = defineEmits<{
  (
    e: "getAddress",
    data: {
      code: string[]; //区域码
      name: string[]; //汉字
      isComplete: boolean; //是否选择完整,方便校验
    }
  ): void;
}>();
let form = reactive<{
  province: string;
  city: string;
  district: string;
}>({
  province: "",
  city: "",
  district: "",
});
interface DistrictList {
  value: string;
  label: string;
  children?: DistrictList[];
}
//切换省份函数
const handleProvinceSelect = () => {
  
  console.log(codeToText[form.province]);
  
    form.city = "";
    form.district = "";
  emit("getAddress", {
    code: [form.province], //区域码
    name: [codeToText[form.province]], //汉字
    isComplete: false,
  });
};
//切换城市函数
const handleCitySelect = () => {

  console.log(codeToText[form.city]);
  
    form.district = "";
  emit("getAddress", {
    code: [form.province, form.city], //区域码
    name: [codeToText[form.province], codeToText[form.city]], //汉字
    isComplete: districtList.value.length == 0 ? true : false,
  });
};
//切换地区函数
const handleAreaSelect = () => {

  console.log(codeToText[form.district]);
  
  emit("getAddress", {
    code: [form.province, form.city, form.district], //区域码
    name: [
      codeToText[form.province],
      codeToText[form.city],
      codeToText[form.district],
    ], //汉字
    isComplete: true,
  });
};
//二级城市列表
const cityList: ComputedRef<DistrictList[]> = computed((): DistrictList[] => {
  if (!form.province) {
    return [];
  }
  let temp = regionData.find((item: any) => {
    return item.value == form.province;
  }); 
  return temp.children ? temp.children : [];
});
//三级地区列表
const districtList: ComputedRef<DistrictList[]> = computed((): DistrictList[] => {
  if (!form.province || !form.city) {
    return [];
  }
  if (cityList.value.length == 0) {
    return [];
  } else {
    let temp = cityList.value.find((item: any) => {
      return item.value == form.city;
    });
    if (temp) {
      return temp.children ? temp.children : [];
    } else {
      return [];
    }
  }
});
</script>
<style scoped>
.areabox {
    width: 800px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
 
}

</style>
1-1.2省市区都选择 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值