通过上一个文章已经成功注册谷歌API并且引入了一个谷歌地球的展示。
现在需要为地球加上一个自定义的图标方法。
下面会演示两种地图方法
1、地图增加自定义坐标图片方法
2、地图更加自定义DIV方法(更灵活)
// 首先引入谷歌依赖
import { Loader } from '@googlemaps/js-api-loader';
initmap()
//初始化谷歌地球
function initmap() {
const loader = new Loader({
apiKey: "你的秘钥",
version: "beta",
});
const mapOptions = {
tilt: 0,
heading: 0,
zoom: 18,
center: { lat: , lng: },
mapId: "你的地图ID",
mapTypeId: "satellite",
'zoomControl': false,
'mapTypeControl': false,
'scaleControl': false,
'streetViewControl': false,
'rotateControl': false,
'fullscreenControl': false
};
//定义地图标点需要的方法
const { Map, InfoWindow } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary( "marker",);
const infoWindow = new InfoWindow();
const mapDiv = document.getElementById("map");
const apiLoader = new Loader(loader);
let marker = null
apiLoader.load();
map = new google.maps.Map(mapDiv, mapOptions);
//摄像头位置初始化
map.moveCamera({
center: new google.maps.LatLng(经纬度,注意需要数字类型值),
zoom: 16,
heading: 0,
tilt: 60,
});
//click事件获得定位
map.addListener("click", (e) => {
console.log('当前经纬度坐标',e.latLng.lat(),e.latLng.lng());
});
//开始自定义图标方法
//maplist的数据位自己定义返回的值
//其中position为{经度,纬度注意值要为数字类型否则不执行}
//title字符必带,可以写自己的id值,emissionType为自己想携带的参数可随便往后面加
maplist.forEach(({ position, title,emissionType}, i) => {
//初始化img
const beachFlagImg = document.createElement("img");
if(emissionType==0){
//照片地址需要为http开头的地址,不需要外网地址127.0.0.1也可以,不能是@或者../引入。
beachFlagImg.src = "http://";
}else{
beachFlagImg.src = "http://";
}
const marker = new AdvancedMarkerElement({
position,
map,
title: `${title}`,
content: beachFlagImg,
gmpClickable: true,//是否允许点击
});
marker.addListener("click", ({ domEvent, latLng }) => {
//点击后可返回当前点位自定义参数
console.log(marker.title)
});
});
//开始自定义DIV方法
//maplistjiaokong为自己处理的需要循环的参数
console.log('处理后的参数',maplistjiaokong)
for (const property of maplistjiaokong) {
//position、title和上面的要求一样
//content是加载自定义方法的关键
const adElement = new AdvancedMarkerElement({
position:property.position,
map,
title: property.channelName,
content: buildContent(property),
gmpClickable: true,
});
adElement.addListener("click", () => {
//摄像头绑定的点击方法
console.log('摄像头被点击了',adElement.title)
});
}
function buildContent(property) {
//首先定义一个DIV做自定义的载体
const content = document.createElement("div");
//定义完方法后通过${property.xxx}的方法将循环中的参数写入的文字和背景图等方法中
//注意div引用的方法也需要是http的地址才行,不能使用相对绝对路径,地址207.0.0.1也可以。
content.innerHTML = `<div class="shexiangboss" style="z-index: 100;height: 80px;position: absolute; right: 10%;height: 10%;z-index: 100;bottom:150px;">
<div style="width: 200px;height:150px;color: white;text-align: center;background: url(http://) center/100% 100% no-repeat;">
<div>${property.channelName}</div>
<img src="${property.alarmImage}" style="width: 95%;margin: auto;padding-top: 5px;height:118px;" alt="">
</div>
<div class="shexiangbottom" style="width: 70px;height: 70px;margin: auto;background: url(http://) center/100% 100% no-repeat;"></div>
</div> `;
return content;
}
}