Label 类
此类表示地图上的文本标注。
构造函数
| 构造函数 | 描述 |
|---|---|
Label(content: string, opts: LabelOptions) | 创建一个文本标注实例。position 参数指定了文本标注所在的地理位置 |
LabelOptions
| 属性 | 类型 | 描述 |
|---|---|---|
| offset | Size | 文本标注的位置偏移值 |
| position | Point | 文本标注的地理位置 |
| enableMassClear | boolean | 是否在调用 map.clearOverlays 清除此覆盖物,默认为 true |
方法
| 方法 | 返回值 | 描述 |
|---|---|---|
setStyle(styles: Object) | void | 设置文本标注样式,该样式将作用于文本标注的容器元素上。其中 styles 为 JavaScript 对象常量,比如:setStyle({ color: "red", fontSize: "12px" }) 注意:如果 css 的属性名中包含连字符,需要将连字符去掉并将其后的字母进行大写处理,例如:背景色属性要写成:backgroundColor |
setContent(content: string) | void | 设置文本标注的内容。支持 HTML |
| setPosition(position: Point) | void | 设置文本标注坐标。仅当通过 Map.addOverlay() 方法添加的文本标注有效 |
| getPosition() | Point | 获取 Label 的地理坐标 |
| setOffset(offset: Size) | void | 设置文本标注的偏移值 |
| getOffset() | Size | 返回文本标注的偏移值 |
setTitle(title: string) | void | 设置文本标注的标题,当鼠标移至标注上时显示此标题 |
| getTitle() | string | 返回文本标注的标题 |
| enableMassClear() | void | 允许覆盖物在 map.clearOverlays 方法中被清除 |
| disableMassClear() | void | 禁止覆盖物在 map.clearOverlays 方法中被清除 |
setZIndex(zIndex: number) | void | 设置覆盖物的 zIndex |
| getMap() | Map | 返回覆盖物所在的 map 对象 |
addEventListener(event: string, handler: Function) | void | 添加事件监听函数 |
removeEventListener(event: string, handler: Function) | void | 移除事件监听函数 |
事件
| 事件 | 参数 | 描述 |
|---|---|---|
| click | {type: string, target: any} | 点击文本标注后会触发此事件 |
| dblclick | {type: string, target: any} | 双击文本标注后会触发此事件 |
| mousedown | {type: string, target: any} | 鼠标在文本标注上按下触发此事件 |
| mouseup | {type: string, target: any} | 鼠标在文本标注释放触发此事件 |
| mouseout | {type: string, target: any} | 鼠标离开文本标注时触发此事件 |
| mouseover | {type: string, target: any} | 当鼠标进入文本标注区域时会触发此事件 |
| remove | {type: string, target: any} | 移除文本标注时触发 |
| rightclick | {type: string, target: any} | 右键点击标注时触发此事件 |
示例
javascript
// 创建文本标注
var label = new BMapGL.Label("这是一个文本标注", {
position: new BMapGL.Point(116.404, 39.915),
offset: new BMapGL.Size(-50, -25)
});
// 添加到地图
map.addOverlay(label);
// 设置样式
label.setStyle({
color: "#333",
fontSize: "16px",
backgroundColor: "#fff",
border: "1px solid #ccc",
padding: "10px",
borderRadius: "3px"
});
// 设置新内容
label.setContent("更新后的文本内容");
// 添加事件监听
label.addEventListener("click", function(e) {
console.log("标注被点击", e);
});常见用途
- 创建基本文本标注
javascript
var label = new BMapGL.Label("基本标注", {
position: new BMapGL.Point(116.404, 39.915)
});
map.addOverlay(label);- 创建带有自定义样式的标注
javascript
var label = new BMapGL.Label("自定义样式标注", {
position: new BMapGL.Point(116.404, 39.915),
offset: new BMapGL.Size(-50, -25)
});
label.setStyle({
backgroundColor: "#fff",
borderRadius: "5px",
padding: "10px",
boxShadow: "0 2px 6px rgba(0,0,0,0.1)"
});
map.addOverlay(label);注意事项
- 设置样式时需要使用驼峰命名法,如
backgroundColor而不是background-color - 支持 HTML 内容,但需要注意 XSS 安全问题
- 偏移值通过
setOffset设置,可用于微调标注位置 - 可以通过
enableMassClear和disableMassClear控制是否允许被批量清除 - 事件处理函数中的
target指向标注本身 - 建议设置合适的
zIndex来控制标注的层级关系
