记录:google map谷歌地图自定义叠加层overlay流程

喻嘉泽
2023-12-01

Google Map自定义叠加层的实现

1、触发:

// 返回结果的数组,拿到有效的值存进数组
let newArr = res.filter((item) => {
  return item.list.length !== 0
})
/*
[{
	id: 110
	latitude: 32.838939245
	list: Array(1)
	longitude: 108.644363426
	name: "中国"
}]
*/
this.createOverlayHandle(newArr)

2、创建自定义叠加层的构造函数

createOverlayHandle (list) { // 创建自定义叠加层
      const _self = this
      USGSOverlay.prototype = new window.google.maps.OverlayView() // 继承overlayView
      function USGSOverlay () { // 存放需要放的属性
        this.list_ = list
        this.divs = []
        this.latLngItem = []
        this.setMap(_self.maps)
      }
      USGSOverlay.prototype.onAdd = function () { // 添加的方法:控制渲染成自定义的模板
        this.getPanes().overlayLayer.innerHTML = ''
        this.list_.forEach((item) => {
          let div = document.createElement('div')
          div.classList.add('custom')
          let H, W
          if (item.list.length <= 5) {
            W = '60px'
            H = item.list.length * 16
          } else {
            W = '120px'
            H = Math.ceil((item.list.length / 2)) * 16
          }
          div.style.cssText = `width: ${W}; height: ${H}px; background-color: rgba(0,0,0,0.5); position: absolute;`
          item.list.forEach((i) => {
            div.innerHTML += `
              <div style="width: 60px; height: 16px; float: left; padding: 1px 1px;">
                <img style="width: 14px; height: 14px; float: left;" src="${require(`@/assets/img/tree_marker_icon/${i.category_icon}.png`)}" />
                <span style="width: calc(100% - 14px); height: 14px; text-align: center; float: left; color: #fff; font-size: 12px; line-height: 14px">${i.nums}</span>
              </div>
            `
          })
          this.divs.push(div)
          this.latLngItem.push(item)
          let panes = this.getPanes()
          panes.overlayLayer.appendChild(div)
        })
      }
      USGSOverlay.prototype.draw = function () { // 方法:绘制,确保控制left top跟随
        this.divs.forEach((item, index) => {
          let latlng = new window.google.maps.LatLng(this.latLngItem[index].latitude, this.latLngItem[index].longitude)
          let overlayProjection = this.getProjection()
          let latLng = overlayProjection.fromLatLngToDivPixel(latlng)
          item.style.left = latLng.x + 'px'
          item.style.top = latLng.y + 'px'
        })
      }
      USGSOverlay.prototype.onRemove = function () { // 方法:删除
        if (document.querySelectorAll('.custom').length !== 0) {
          document.querySelectorAll('.custom')[0].parentNode.innerHTML = ''
        }
        this.divs = []
        this.overlay = null
      }
      this.overlay = new USGSOverlay() // 创建实例化对象
      this.overlay.draw()
      this.overlay.onAdd()
    }

官网案例examplehttps://developers.google.cn/maps/documentation/javascript/examples/overlay-simple
备注:代码需要的数据,需要渲染的结构之后根据需求自行调整修改,此代码为实现当前需求。

 类似资料: