'use strict' const init = (L) => { L.CustomPopup = L.Popup.extend({ _initLayout: () => { // 此处生成的容器,Leaflet会根据其类名自动适配Transform,匹配样式,所以如果要自定义的话,该部分样式要自己重写,我这里只解决了自适应容器的问题,以下采用原生容器,所以后面我会加上样式覆盖。 let prefix = 'leaflet-popup' let container = (this._container = L.DomUtil.create( 'div', prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-animated' )) let wrapper = container this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper) L.DomEvent.disableClickPropagation(wrapper) .disableScrollPropagation(this._contentNode) .on(wrapper, 'contextmenu', L.DomEvent.stopPropagation) this._tipContainer = L.DomUtil.create( 'div', prefix + '-tip-container', container ) this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer) }, // 位置更新 _updatePosition: () => { if (!this._map) { return } let pos = this._map.latLngToLayerPoint(this._latlng) let offset = L.point(this.options.offset) let anchor = [0, 0] if (this._zoomAnimated) { setPosition(this._container, pos.add(anchor)) } else { offset = offset.add(pos).add(anchor) } let bottom = (this._containerBottom = -offset.y) let left = (this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x) // bottom position the popup in case the height of the popup changes (images loading etc) this._container.style.bottom = bottom + 'px' this._container.style.left = left + 'px' }, // 重写层级变化触发更新 _animateZoom: (e) => { let pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center) let anchor = [0, 0] setPosition(this._container, pos.add(anchor)) } }) // 重写setTransform,由于不再固定宽度,所以增加translateX(-50%)水平居中 const setTransform = (el, offset, scale) => { let pos = offset || new L.Point(0, 0) el.style[L.DomUtil.TRANSFORM] = (L.Browser.ie3d ? 'translate(' + pos.x + 'px,' + pos.y + 'px,0) translateX(-50%)' : 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0) translateX(-50%)') + (scale ? ' scale(' + scale + ')' : '') } // 因为重写了setTransform,所以setPosition也要重新指向方法 const setPosition = (el, point) => { el._leaflet_pos = point if (L.Browser.any3d) { setTransform(el, point) } else { el.style.left = point.x + 'px' el.style.top = point.y + 'px' } } } export default { init }