截至2025年03月21日天地圖的Marker不支持添加Label; 同時Label和Icon是不支持自定義HTMLElement只支持String;目前只有InfoWindow支持自定義HTMLElement;
效果圖
React核心api
import ReactDOM from 'react-dom/client'
const content = document.createElement('div');
ReactDOM.createRoot(content).render((<CurLineInfoWindowContent optionsClick={curInfoWindowClick}/>
));
天地圖InfoWindow
// 創建
const infoWin = new T.InfoWindow();
// 開啟
map.openInfoWindow(infoWin, e.lnglat)
// 關閉
map.closeInfoWindow(infoWin);
// 插入自定義
infoWin.setContent(content: String | HTMLElement);
場景模擬: 點擊線彈出編輯和刪除
自定義組件_編輯/刪除
import style from './style.module.less';
const CurLineInfoWindowContent = ({optionsClick}: any) => {// 你的React組件,包含編輯和刪除按鈕return (<div className={style.custom_line_window_wrap}>{/* <span className={style.custom_line_window_name}>路線: {linePathNum} (個點)</span> */}<button onClick={(event: any) => {const currentTarget = event.currentTarget;currentTarget.disabled = true;setTimeout(() => { currentTarget.disabled = false; }, 250);optionsClick(0);}}>點編輯</button><button className={style.del_button}onClick={(event: any) => {const currentTarget = event.currentTarget;currentTarget.disabled = true;setTimeout(() => { currentTarget.disabled = false; }, 250);optionsClick(1);}}>刪除</button></div>);
};
天地圖創建線和綁定事件
/* 創建線 */
var points = [];
points.push(new T.LngLat(116.41239, 39.97569));
points.push(new T.LngLat(116.412799, 39.9068));
points.push(new T.LngLat(116.32970, 39.92940));
points.push(new T.LngLat(116.385440, 39.90610));
var polyline = new T.Polyline(points , {weight: 6,color: '#3366FF'
});
/* 創建infoWindow */
const infoWin = new T.InfoWindow();
// 創建一個div
const content = document.createElement('div');
// 綁定自定義組件事件
const curInfoWindowClick(action: number){switch(action){case 0:{ // 處理編輯邏輯polyline.enableEdit();}break;case 1:{ // 處理刪除邏輯map.removeOverLay(polyline);}break;default:break;}
}
// 將React組件渲染到DOM
ReactDOM.createRoot(content).render((<CurLineInfoWindowContent optionsClick={curInfoWindowClick}/>
));
// 插入到infoWindow
infoWin.setContent(content);
/* 綁定事件 */
// 綁定點擊事件
polyline.addEventListener('click', (e: any) => {map.openInfoWindow(infoWin, e.lnglat)
});
// 如果線被移除了_順手把彈窗給隱藏掉
polyline.addEventListener('remove', (e: any) => {map.closeInfoWindow(infoWin);
});