在vue3中引入高德地图API要实现的功能

  1. 设置地图的显示样式
  2. 实现点击地图添加标记、点击地图获取详细地址和经纬度
  3. 输入框搜索获取相关地区提示(下拉框,选中后进行标记,视角移动到相对位置)
  4. 输入框输入内容,回车获取详细地址和经纬度

1、准备工作

先进入高德开放平台,跟着步骤注册账号,创建应用
创建时服务平台要选择【web端(JS API)】,如果选其他服务有些功能用不了(比如后面的地址逆解析)。
官网示例地址:地图的创建-生命周期-示例中心-JS API 示例 | 高德地图API (amap.com)

2、用npm/yarn下载包,初始化地图

在Vue 3中引入高德地图,你可以按照以下步骤进行操作:
在项目目录中使用npm或yarn安装高德地图的JavaScript API库。你可以使用以下命令之一:

npm install @amap/amap-jsapi-loader
yarn add @amap/amap-jsapi-loader

2.1、注意事项:

1、必须要有安全密钥,不然有的api调用返回为undefined

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "95869xxxxxxxxxxxxxxxxx53df87dfb",
};

3、组件代码(需要替换密钥和key)


<template>
	<div id="container"></div>
</template>
 
<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader'
import { onMounted, watch, defineProps,defineEmits,onUnmounted,ref, reactive } from 'vue'
import { log } from 'console'
 // 使用defineEmits创建名称,接受一个数组
const emit = defineEmits(["clickChild"]);
const props = defineProps({
  childValue: {
    default:''
  },
  infos:{
	type:Object,
	default:{
      lng:undefined,
	  lat:undefined
    }
  }
});
let isTrue=ref(false)
let isProduction=ref(true)
let options=ref([])
let map:any= null
//标记点
let marker=''
// 地址逆解析
let geoCoder:any=null
// 位置信息
let form= ref({
	lng: "",
	lat: "",
	address: "",
	//地区编码
	adcode: "",
})
let AutoComplete:any=null
window._AMapSecurityConfig = {
	securityJsCode: '95869xxxxxxxxxxxxxxxxx53df87dfb',
}
watch(
  () => props.childValue,
  (newValue, oldValue) => {
	if(isProduction.value){
		// 地理编码
		geoCode()
	}else{
		// 搜索提示
		remoteMethod(newValue)
	}
  }
);

watch(
  () => isTrue.value,
  (newValue, oldValue) => {
	if(newValue&&props.infos.lng){
		// 获取经纬度
		form.value.lng = props.infos.lng;
		form.value.lat = props.infos.lat;
		// 清除点
		removeMarker();
		// 标记点
		setMapMarker();
	}
  }
);
watch(
  () => props.infos.lng,
  (newValue, oldValue) => {
	if(newValue&&isTrue.value){
		// 获取经纬度
		form.value.lng = props.infos.lng;
		form.value.lat = props.infos.lat;
		// 清除点
		removeMarker();
		// 标记点
		setMapMarker();
	}
  }
);
// 搜索
function remoteMethod(query:any) {
	if (query !== "") {
		AutoComplete.search(query, (status:any, result:any) => {
		options.value = result.tips;
		let obj={
			options:options.value
		}
		emit("clickChild", obj);
	} else {
		options.value = [];
	}
}

// 标记点
function setMapMarker() {
	// 自动适应显示想显示的范围区域
	map.setFitView();
	marker = new AMap.Marker({
		map: map,
		position: [form.value.lng, form.value.lat],
	});
	map.setFitView();
	// // 逆解析地址
    // toGeoCoder();
	map.add(marker);
}
// 清除点
function removeMarker() {
	if (marker) {
		map.remove(marker);
	}
}

//正解析地址
function geoCode(){
	let geocoder = new AMap.Geocoder({
        // city: "010", //城市设为北京,默认:“全国”
        radius: 1000 //范围,默认:500
    });
	let address = props.childValue;
	geocoder.getLocation(address, function(status:any, result:any) {
		if (status === 'complete'&&result.geocodes.length) {
			var e = result.geocodes[0].location
			// 获取经纬度
			form.value.lng = e.lng;
			form.value.lat = e.lat;
			// 清除点
			removeMarker();
			// 标记点
			setMapMarker();
			let obj={
				ParkLongitude:form.value.lng+'',
				ParkLatitude:form.value.lat+'',
				address:address
			}
			emit("clickChild", obj);
		}else{
			// log.error('根据地址查询位置失败');
		}
	});
}
// 逆解析地址
function regeoCode() {
	
	let geocoder = new AMap.Geocoder({
        // city: "010", //城市设为北京,默认:“全国”
        radius: 1000 //范围,默认:500
    });
	let lnglat = [form.value.lng,form.value.lat];
	geocoder.getAddress(lnglat, function(status:any, result:any) {
		if (status === 'complete'&&result.regeocode) {
			let address = result.regeocode.formattedAddress;
			// '解析的地址',address;
			let obj={
				ParkLongitude:form.value.lng+'',
				ParkLatitude:form.value.lat+'',
				address:address
			}
			emit("clickChild", obj);
		}else{
			// log.error('根据经纬度查询地址失败')
		}
	});
}

//获取详细地址
function toGeoCoder() {
	AMap.plugin('AMap.Geolocation', function() {
        let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:5s
            position:'RB',    //定位按钮的停靠位置
            offset: [form.value.lng, form.value.lat], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
			needAddress:true,
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status:any, result:any){
            if(status=='complete'){
                // onComplete(result)
            }else{
                // onError(result)
            }
        });
    });
}
onMounted(() => {
	AMapLoader.load({
		key: '95869xxxxxxxxxxxxxxxxx53df87dfb',
		version: '2.0',
		// 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete",'AMap.Geolocation'],
	})
	.then((AMap) => {
		map = new AMap.Map('container', {
			viewMode: '3D',
			zoom: 11,
			mapStyle: 'amap://styles/grey', //设置地图的显示样式
			// center: [116.397428, 39.90923],
		})
		// 搜索提示插件
		AutoComplete = new AMap.AutoComplete({ city: "全国" });
		//为地图注册click事件获取鼠标点击出的经纬度坐标
		map.on('click', function(e:any) {
			map.value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
			// '点击位置:', e.lnglat;
			// 获取经纬度
			form.value.lng = e.lnglat.lng;
			form.value.lat = e.lnglat.lat;
			// 清除点
			removeMarker();
			// 标记点
			setMapMarker();
			regeoCode();
		});

		isTrue.value=true

	})
	.catch((e) => {
	})
})
onUnmounted(() => {
	map && map.destroy();
})
</script>
<script lang="ts">
// 起名字,否则每个组件在开发者工具中都为index
export default {
  name: "Maps",
};
</script>
<style scoped>
#container {
	width: 100%;
    height: 100%;
}
</style>
12-21 20:48