效果图
1、首先要有个高德地图的开发者账号,没有的直接注册就行,这个是地址高德开放平台 | 高德地图API
2、在右侧菜单点击应用管理,我的应用,然后创建新的应用
3、这里随便写个名称,然后选择类型,点击创建
4、然后在我的应用里就可以看到了,然后添加key
5、填写名称,选择对应的服务平台,然后点击提交
6、等会儿我们在项目里会用到我们的key以及秘钥
7、打开项目控制台下载地图依赖包
npm i @amap/amap-jsapi-loader
8、引入
window._AMapSecurityConfig = {
securityJsCode: "秘钥",
};
import AMapLoader from "@amap/amap-jsapi-loader";
9、在页面新建盒子
<!-- 地图 -->
<div id="container"></div>
10、必须要跟这个盒子设置宽高
#container {
width: 100%;
height: 450px;
}
11、JS部分
var map = {}; // 最好在data外声明要不然地图会一卡一卡
var markers = []; // 最好在data外声明要不然地图会一卡一卡
export default {
name: "",
components: {},
data() {
return {
// map: null, //初始化 map 对象
// markers: [], // 存储标点
// 标点列表
mapData:[
{
name: '测试',
longitude: 113.991682, // 经纬度
latitude: 29.249937, // 经纬度
content:'123123123@163.com',
// img:''
},
],
};
},
methods: {
initMap() {
const MAP_PLUGINS = ["AMap.Marker"];
AMapLoader.load({
key: "你的key",
version: "2.0",
plugins: MAP_PLUGINS,
})
.then((AMap) => {
const map = new AMap.Map("container", {
viewMode: "3D", //是否为3D地图模式
terrain: true,
zoom: 13,
center: [113.94,28.22], //地图初始展示中心位置
mapStyle: 'amap://styles/normal',
features: ['road','point'],
});
this.map = map;
// 创建点标点
// this.createMarkers();
this.markPoints()
})
.catch((error) => {
// console.log(error);
});
},
markPoints() {
this.mapData.forEach(item => {
// 创建一个 Marker 实例:
const marker = new AMap.Marker({
position: new AMap.LngLat(item.longitude, item.latitude), // 经纬度对象,也可 以是经纬度构成的一维数组[lng, lat]
});
// 将创建的点标记添加到已有的地图实例:
this.map.add(marker);
this.map.setFitView();
//给标记点添加事件
marker.on('click', (e) => {
this.setInfoWindows(e, item)
})
});
},
//显示的弹出框组件
setInfoWindows(e, item) {
console.log(item)
// 信息窗体的内容
let content = [
// e.pos[0],e.pos[1],
`<div style='\'padding:0px' 0px = '' 4px; \'=''><b>${item.name}</b>`,
"电话 : 123123123",
`邮箱 :${item.content}`,
"地址 : 测试地址</div></div>",
// `<img src=${item.img} alt="" style="width: 100px;height: 100px">`
];
// 创建 infoWindow 实例
let infoWindow = new AMap.InfoWindow({
content: content.join("<br>") //传入 dom 对象,或者 html 字符串
});
// 打开信息窗体
let dd = this.map.getCenter()
// dd.pos = [e.pos[0], e.pos[1]]
dd.lat = item.latitude
dd.lng = item.longitude
console.log(dd)
infoWindow.open(this.map, dd);
},
//点击获取经纬度
latitude() {
this.map.on('click', function (ev) {
// console.log(ev)
// 触发事件的对象
let target = ev.target;
// 触发事件的地理坐标,AMap.LngLat 类型
let lnglat = ev.lnglat;
// 触发事件的像素坐标,AMap.Pixel 类型
let pixel = ev.pixel;
// 触发事件类型
let type = ev.type;
console.log(target, lnglat, pixel, type)
});
},
}