1、安装Echarts高德地图扩展echarts-extension-amap;
npm i echarts-extension-amap --save
2、引入Echarts和高德地图;
npm i echarts --save
npm i @amap/amap-jsapi-loader --save
3、需要先创建高德地图实例,才能调用Echarts API来引入地图;
useAMap.ts
import * as AMapLoader from "@amap/amap-jsapi-loader";
interface plugins {
loaderPlugins?: string[];
AMapUIPlugins?: string[];
}
const getMapKeyByOrgId = () => {
const key = "[申请的高德key]";
// @ts-ignore
window._AMapSecurityConfig = {
securityJsCode: "[key对应安全密钥]",
};
return key;
};
export async function useAMapLoader(
plugins: plugins = { loaderPlugins: [], AMapUIPlugins: [] }
) {
const key = getMapKeyByOrgId();
return await AMapLoader.load({
key, // 申请好的Web端开发者Key,首次调用 load 时必填
version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: plugins.loaderPlugins, // 需要使用的的插件列表,如比例尺'AMap.Scale'等
AMapUI: {
// 是否加载 AMapUI,缺省不加载
version: "1.1", // AMapUI 缺省 1.1, JSAPI v2.0 版本需要使用AMapUI 组件库的 v1.1版本。
plugins: plugins.AMapUIPlugins, // 需要加载的 AMapUI ui插件
},
});
}
3、创建高德地图实例并在Echarst引入高德
<template>
<!-- 地图实例 -->
<div id="map-contain" class="map-contain"></div>
<!-- echarts绘制地图 -->
<div id="echarts-2d-map" class="echarts-2d-map" ref="echarts2dContain"></div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import "echarts-extension-amap";
import { useAMapLoader } from './useAMap';
const echarts2dContain = ref<HTMLElement>();
let amap: AMap.Map;
// init amap
const initMap = async () => {
if (!amap) {
amap = await useAMapLoader({ loaderPlugins: ['AMap.DistrictSearch'] });
const mapOption: AMap.MapOptions = {
center: [85.817916, 41.662527],
zoom: 17,
// @ts-ignore
forceVector: true,
};
new AMap.Map('map-contain', mapOption);
}
}
// init echarts-2d
const initEcharts2d = (districtData) => {
const myChart = echarts.init(echarts2dContain.value, 'echarts-2d-map');
myChart.setOption({
amap: {
// 高德地图中心经纬度
center: [85.817916, 41.662527],
// 高德地图缩放
zoom: 5.8,
// 启用resize
resizeEnable: true,
// 移动过程中实时渲染 默认为true 如数据量较大 建议置为false
renderOnMoving: false,
// mapStyle: 'amap://styles/dark',
// viewMode: '3D',
// pitch: 60,
},
});
// @ts-ignore 获取到高德地图实例
const mapModel = myChart.getModel().getComponent('amap').getAMap();
// 调用高德API
}
onMounted(async () => {
await initMap();
await initEcharts2d();
})
</script>
<style scoped lang="less">
.echarts-2d-map {
height: 90vh;
width: 90vw;
}
</style>
获取到的变量 mapModel 就是在Echarts中引入的地图实例,可直接调用高德API进行操作。
例:
// 监听地图缩放
mapModel.on("zoomend", () => {
const totalZoom = mapModel.getZoom(); //获取地图级别
console.log('Zoom', totalZoom);
});
以上。
标签:const,地图,高德,API,amap,plugins,echarts From: https://www.cnblogs.com/wttt123/p/18558916