首先注册高德key
https://console.amap.com/dev/key/a
vue项目中安转地图包
pnpm i @amap/amap-jsapi-loader -S
先说最重要核心,踩雷过
页面中需写入以下代码,现在注册的高德key要求强制写入安全密钥
window._AMapSecurityConfig = {securityJsCode: 'c3d717e94ace33f46e7354f5a4633faa',
};
业务代码
<template><el-dialog v-model="isVisible" title="考勤地点" width="70%"><div class="cotainer"><div class="module-search"><div class="title">地点:</div><div class="box-ipt"><el-input v-model="locationName" style="width: 420px" placeholder="请输入位置" /></div><el-button type="primary">搜索</el-button></div><div ref="mapRef" class="map"></div></div><template #footer><span class="dialog-footer"><el-button @click="onClose">关闭</el-button><el-button v-if="type !== 'view'" type="primary" @click="onConfirm">确认</el-button></span></template></el-dialog>
</template>
<script setup>
import { defineComponent, toRefs, reactive, getCurrentInstance, ref, onMounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {securityJsCode: '安全密钥',
};const initMap = () => {AMapLoader.load({key: '申请好的Web端开发者Key', // 申请好的Web端开发者Key,首次调用 load 时必填plugins: ['AMap.Scale', 'AMap.Geocoder'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等AMapUI: {version: '1.1',},}).then((AMap) => {const map = new AMap.Map(mapRef.value, {viewMode: '2D',zoom: 12,center: [116.295797, 40.042976],resizeEnable: true, // 监控地图容器尺寸变化,默认值为falseexpandZoomRange: true, // 支持可以扩展最大缩放级别,和zooms属性配合使用,设置为true的时候,zooms的最大级别在PC上可以扩大到20级});let marker = new AMap.Marker({icon: '',position: lnglatData.value,offset: new AMap.Pixel(-12, -32), // //标记点相对偏移量,可以固定其地址,不随着地图缩放而偏移draggable: !mapDisabled.value, // 点标记对象是否可拖拽移动defaultCursor: 'pointer',});map.add(marker);let geocoder = new AMap.Geocoder({city: '010', // 城市设为北京,默认:“全国”radius: 1000, // 范围,默认:500});map.on('click', (e) => {console.log(mapDisabled.value, '---mapDisabled.value');if (mapDisabled.value === true) {// return;} else {let arr = [];arr[0] = e.lnglat.lng.toString();arr[1] = e.lnglat.lat.toString();regeoCode(arr);}});function regeoCode(e) {let lnglat = e;console.log(e, '---e');lnglatData.value[0] = e[0];lnglatData.value[1] = e[1];map.add(marker);marker.setPosition(lnglat);geocoder.getAddress(lnglat, (status, result) => {if (status === 'complete' && result.regeocode) {let address = result.regeocode.formattedAddress;locationName.value = address;console.log(address, '---address');}});}}).catch((e) => {console.log(e, 1111);});
};</script>