高德地图实现地图打点,点击后展示小弹框
准备工作 下载AMapLoader
“@amap/amap-jsapi-loader”: “^1.0.1”,
创建高德地图
import AMapLoader from '@amap/amap-jsapi-loader';
AMapLoader.load({
key: '6b40f6e6182ec3e892bf66f5656c4b5d',
plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch'],
}).then((AMap) => {
this.AMap = AMap; // AMap高德地图类 amap高德地图创建的实例
this.map = new AMap.Map('mapDiv', {
zoom: 11, // 级别
resizeEnable: true,
zooms: [3, 18],
mapStyle: 'amap://styles/4f42a4b0bb196fe1bf0cd6243a89c268', // 设置地图的显示样式
});
})
setMarker() {
// this.markerList 为需要打点的数组对象
this.markerList = this.dataList.map((marker) => {
if (!(marker.longitude && marker.latitude)) return null;
// 创建图标
const icon = new this.AMap.Icon({
size: new this.AMap.Size(33, 35), // 图标尺寸
image: zhengchang, // Icon的图像
// imageOffset: new this.AMap.Pixel(0, -60), // 图像相对展示区域的偏移量,适于雪碧图等
imageSize: new this.AMap.Size(33, 35), // 根据所设置的大小拉伸或压缩图片
});
// 将 Icon 实例添加到 marker 上:
// gcoord 为地图坐标转换工具
const mar = new this.AMap.Marker({
position: gcoord.transform([marker.longitude, marker.latitude],
gcoord.WGS84, gcoord.AMap),
// offset: new this.AMap.Pixel(-10, -10),
icon,
id: marker.id,
// extData: marker,
// zoom: 13,
});
// 将其他信息设置到特征点上
mar.setExtData(marker);
// 特征点的点击事件 设置小弹框
mar.on('click', (e) => {
this.setLabels(e.target.getExtData());
});
return mar;
})
// 将点添加到地图上
this.map.add(this.markerList);
},
setLabels(item) {
// vueComponent 只需要引入 不需要注册
const InfoContent = Vue.extend(vueComponent);
const component = new InfoContent(
{
// 给vueComponent传入参数 ,vueComponent通过props接收
propsData: {
setData: {
...item,
},
},
},
// 挂载
).$mount();
this.creatLabel(component.$el, gcoord.transform([item.longitude, item.latitude],
gcoord.WGS84, gcoord.AMap), [8, -23]);
},
// 创建InfoWindow
creatLabel(content, center, offset = [0, 0]) {
const infoWindow = new this.AMap.InfoWindow({
content, // 使用默认信息窗体框样式,显示信息内容
offset: new this.AMap.Pixel(offset[0], offset[1]),
closeWhenClickMap: true,
});
infoWindow.open(this.map, center);
},