Leaflet 自定義 Popup (自定義Marker標記氣泡)
之前在寫項目的過程中遇到一個這樣的需求,找了很多文章都沒有能直接解決這個問題
我們開始解決問題吧:
首先我們在地圖上加載marker 這裏就不過多描述了 直接進入正題 先把popup這一塊的文檔放在這裏
Options參數選項
Option參數 | 參數類型 | 默認值 | 說明 |
---|---|---|---|
maxWidth |
Number |
300 |
彈窗的最大寬度,單位爲像素 |
minWidth |
Number |
50 |
彈窗的最小寬度,單位爲像素 |
maxHeight |
Number |
null |
如果設置,如果內容超過此高度時,則在彈出窗口中顯示滾動條。 |
autoPan |
Boolean |
true |
如果您不希望地圖進行平移動畫以適應打開的彈出窗口, 請將其設置爲false。 |
autoPanPaddingTopLeft |
Point |
null |
執行自動平移後,彈窗和地圖視圖左上角之間的邊距。 |
autoPanPaddingBottomRight |
Point |
null |
執行自動平移後,彈窗和地圖視圖右下角之間的邊距。 |
autoPanPadding |
Point |
Point(5, 5) |
相當於將左上角和右下角的自動平移填充設置爲相同的值。 |
keepInView |
Boolean |
false |
如果你想防止用戶在屏幕打開時彈出屏幕上的彈出窗口,將其設置爲true. |
closeButton |
Boolean |
true |
彈窗中是否存在關閉按鈕 |
closeOnClick |
Boolean |
* |
如果要覆蓋用戶在地圖上單擊的彈出窗口關閉的默認行爲,請設置它。默認爲Map的closePopupOnClick選項。 |
autoClose |
Boolean |
true |
如果在打開另一個彈窗時,是否自動關閉之前的彈窗. |
className |
String |
'' |
要分配給彈窗的自定義的css類名 |
我們要用到的就是 className
參數
- 添加/新增 Marker
let marker = L.marker([50.5, 30.5]).addTo(map)
- 給 Marker 添加 Popup 氣泡
marker.bindPopup("我是popup").openPopup(); // openPopup 是自動打開氣泡
- 我們給氣泡綁定 自定義class 並將內容填寫進去
marker.bindPopup(`<span class="cd-span">發佈消息</span>
<span class="cd-span">當前信息</span>
<span class="cd-span">實時狀態</span>`, { className: 'mypopup' }).addTo(map)
- 接下來設置 mypopup 改變popup位置 有一些關閉按鈕,包括氣泡下方的小三角指示表都可以通過css屬性display:none 搞定
/* popup彈窗位置 */
.mypopup {
bottom: -120px !important;
left: -81px !important;
}
- 這裏是我氣泡摸樣的css 我個人的思路是這樣的 :
- 首先將氣泡變成圓形,然後將背景色設置爲透明
- 給圓形增加邊框
- 文字 、分割線 都是用的定位 這裏分割線我用僞類寫的利用偏移將它勉強看着舒服一點(不要在意細節沒有精準三等分)
.mypopup .leaflet-popup-content-wrapper {
width: 160px;
height: 160px;
border-radius: 50%;
border: 55px solid rgb(83, 115, 145);
background-color: rgba(0, 0, 0, 0.24);
}
.cd-span {
position: absolute;
width: 30px;
font-size: 14px;
text-align: center;
line-height: 15px;
}
.cd-span:nth-child(1) {
color: #fff;
top: 13px;
left: 65px;
}
.cd-span:nth-child(1):active {
color: rgb(152, 199, 218);
}
.cd-span:nth-child(1):before {
content: "";
position: absolute;
width: 40px;
height: 1px;
border-bottom: 1px dashed rgb(180, 193, 204);
transform: translate3d(40px, 41px, 0px) rotate(-33deg);
}
.cd-span:nth-child(2) {
color: #fff;
top: 92px;
left: 20px;
}
.cd-span:nth-child(2):active {
color: rgb(152, 199, 218);
}
.cd-span:nth-child(2):before {
content: "";
position: absolute;
width: 40px;
height: 1px;
border-bottom: 1px dashed rgb(180, 193, 204);
transform: translate3d(-6px, -39px, 0px) rotate(30deg);
}
.cd-span:nth-child(3) {
color: #fff;
top: 92px;
left: 110px;
}
.cd-span:nth-child(3):active {
color: rgb(152, 199, 218);
}
.cd-span:nth-child(3):before {
content: "";
position: absolute;
width: 40px;
height: 1px;
border-bottom: 1px dashed rgb(180, 193, 204);
transform: translate3d(-50px, 40px, 0px) rotate(-90deg);
}