首先安装 @amap/amap-jsapi-loader
官网教程
mapContainer.vue
<template><div class="container-map" :style="styleObj"><!-- @change="changeInput" type="text" --><a-input id='tipinput' v-model:value="inputValue" @change="changeInput"></a-input><div id="container" ref="container" tabindex="0"></div><div id="panel"></div></div>
</template>
<script setup>
import { onMounted, onUnmounted, getCurrentInstance, ref, inject, watch, toRefs, reactive } from 'vue'
import { useRouter } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader';
import { keyGD, passwordGD } from "@/core/gaodekey.js";
import { message } from "ant-design-vue";
import utils from "@/core/utils.js";const router = useRouter()
const container = ref(null)
let mapObj = null
let placeSearch = {}
let mapModule = null
let autoComplete = null
const inputValue = ref('')
// 当前位置
const currentPosition = ref({})watch(() => props.value,(n) => {if (!n) {inputValue.value = undefined;} else {inputValue.value = n;}},{ immediate: true }
);
const emits = defineEmits(["getPosition", 'addMarker']);
const props = defineProps({replenishmentMapList: {type: Array,default: () => [],},styleObj: {type: Object,default: () => { }},value: {},
})const changeInput = (target) => {setTimeout(() => {emits("update:value", target.target._value);}, 500)
}
// 添加点位
const addMarker = (pointArray) => {// console.log(pointArray, "pointArray")clearMap()// 创建不同显示的iconpointArray.forEach((marker) => {new AMap.Marker({map: mapObj,position: [marker.lng, marker.lat],icon: new mapModule.Icon({ image: marker.icon || '', size: [25, 34], imageSize: [25, 34] }),offset: new AMap.Pixel(-13, -30)});})// 移动点位中心点mapObj.setFitView();
}
// 清除地图所有覆盖物
const clearMap = () => {mapObj.clearMap();
}
// 初始化地图
const initMap = () => {AMapLoader.load({key: keyGD, // 申请好的Web端开发者Key,首次调用 load 时必填version: '2.0',// 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geolocation"],}).then((AMap) => {console.log(AMap, 'AMap')// 保存AMap实例mapModule = AMapconst map = new AMap.Map('container', {// 设置地图容器id// viewMode: '3D', // 默认2d地图模式zoom: 12, // 初始化地图级别zooms: [5, 30],// 可以设置初始化当前位置// center: [116.397428, 39.90923],resizeEnable: true})mapObj = maplet geolocation = new AMap.Geolocation({enableHighAccuracy: true,//是否使用高精度定位,默认:truetimeout: 10000, //超过10秒后停止定位,默认:5sposition: 'RB', //定位按钮的停靠位置offset: [10, 20], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点});mapObj.addControl(geolocation)geolocation.getCurrentPosition((status, result) => {if (status == 'complete') {console.log(result, 'result你好')const { lng, lat } = result.positioncurrentPosition.value = { lng, lat }emits('getPosition', [lng, lat])addMarker([{ lng, lat }])} else {message.error('定位失败')}})// 搜索功能toSearch()}).catch((e) => {console.log(e)})
}
const select = (e) => {const { poi } = edebuggerconst poiName = e.poi.nameplaceSearch.setCity(e.poi.adcode)// 获取当前的坐标 115.644865,40.223472// lng lat const { lng, lat } = e.poi.locationautoComplete.search(poiName, function (status, result) {if (status === 'complete' && result.info === 'OK') {console.log(result, 'result')addMarker([{ lng, lat }])// 获取搜索到的点位emits('getPosition', [lng, lat])emits('getPositionInfo', poi)}}) // 关键字查询查询
}
const toSearch = () => {const autoOptions = {// input 为绑定输入提示功能的input的DOM ID,注意这个id要个搜索输入框的id一致input: 'tipinput'}autoComplete = new AMap.AutoComplete(autoOptions)placeSearch = new AMap.PlaceSearch({map: mapObj, //展现结果的地图实例})// console.log(placeSearch, 'placeSearch')autoComplete.on('select', select)// 注册监听,当选中某条记录时会触发
}onMounted(() => {window._AMapSecurityConfig = {securityJsCode: passwordGD // 申请key对应的秘钥 -> 注意了,如果不搭配密钥使用,搜索将没有结果}initMap() // 初始化地图
})
onUnmounted(() => {map?.destroy();
})
// watch(propData,(newVal,oldVal)=>{})
defineExpose({addMarker,
})
</script><style scoped>
.container-map {padding: 0px;margin: 0px;width: 50%;height: 500px;#container {width: 100%;height: 100%;}
}
</style>