web端基於百度地圖,實現自定義圓形頭像標柱
-
項目需求
基於百度地圖,在當前用戶的位置上,呈現用戶圓形的頭像。並附加一個水滴狀的背景圖。如圖所示:
-
基本思路
原本打算通過BMap.Icon分別來添加水滴背景和頭像,並用疊加的方式來顯示。但是後臺返回的頭像是矩形,API裏面也沒有找到圓角化功能。所以,此處使用自定義標柱的方式來實現該功能。(如果後臺返回的圖片爲圓形,建議用疊加的方式) -
具體實現
第一步:自定義頭像覆蓋物的構造函數
我們希望通過 “位置”、“頭像資源”、“頭像大小” 來確定一個具體的標柱。所以將該3個屬性作爲參數並實現一個構造函數function CircleImgOverlay(point, headerImg, { width = 50, height = 65 }) { this._point = point; this._headerImg = headerImg; this._width = width; this._height = height; }
第二步:繼承BMap.Overlay基類,實現該基類的功能方法
CircleImgOverlay.prototype = new BMap.Overlay();
第三步:自定義初始化方法
實現initialize方法,當調用map.addOverlay方法時,API會調用此方法。這裏也是我們自定義標柱的具體實現CircleImgOverlay.prototype.initialize = function(map){ this._map = map; var divBox = document.createElement("div"); var divImg = document.createElement("div"); divBox.style.position = "absolute"; divBox.style.width = this._width + "px"; divBox.style.height = this._height + "px"; divBox.style.backgroundImage = "url(./images/header_bg.png)"; divBox.style.backgroundSize = "100% 100%"; divImg.style.position = "absolute"; divImg.style.backgroundImage = `url(${this._headerImg})`; divImg.style.left = "10%"; divImg.style.top = "7%"; divImg.style.width = "80%"; divImg.style.height = "60%"; divImg.style.borderRadius = "50%"; divImg.style.backgroundSize = "cover"; divImg.style.border = "2px solid #ffffff"; divBox.appendChild(divImg); // 將div添加到覆蓋物容器中 map.getPanes().markerPane.appendChild(divBox); // 保存div實例 this._div = divBox; // 需要將div元素作爲方法的返回值,當調用該覆蓋物的show、 // hide方法,或者對覆蓋物進行移除時,API都將操作此元素。 return divBox; }
第四步:實現繪製方法
到目前爲止,我們僅僅把覆蓋物添加到了地圖上,但是並沒有將它放置在正確的位置上。具體的位置偏移根據自己的背景圖片大小進行確定var position = this._map.pointToOverlayPixel(this._point); this._div.style.left = position.x - this._width / 2 + "px"; this._div.style.top = position.y - this._height * 7 / 10 + "px";
第五步:方法調用
var headerImg = new CircleImgOverlay(data.points[0], _self.info.avatar, {}); this.map.addOverlay(headerImg);
-
結果展示
-
更多擴展
請參閱官方文檔