ArcGIS API for Javascript GraphicsLayer实现带背景色的标注

TextSymbol的backgroundColor属性:标签边界框的背景颜色,仅支持 MapImageLayer

本文章使用SimpleMarkerSymbol的path属性实现文字的背景色。给path赋值一个长方形的svg路径,根据文字内容设置宽度和高度。

效果图:

代码:
/**
 * 创建带背景框标注的点要素图层(将map和view放在window里)
 * @param {Object} options
 * --@param {String} id GraphicsLayer的id
 * --@param {String} title GraphicsLayer的title
 * --@param {Array} data 空间数据
 * --@param {Object} attr 属性说明
 * ----@param {String} x 坐标x值的属性名
 * ----@param {String} y 坐标y值的属性名
 * ----@param {String} name 名称标注的属性名
 */
function bgLabelPoint(options) {
  if (window.map.findLayerById(options.id)) {
    window.map.findLayerById(options.id).removeAll()
  } else {
    var layer = new GraphicsLayer({
      id: options.id,
      title: options.title
    })
    window.map.add(layer)
  }
  options.data.forEach((item) => {
    if (item[options.attr.x]) {
      // geometry
      var point = {
        type: 'point',
        x: parseFloat(item[options.attr.x]),
        y: parseFloat(item[options.attr.y]),
        spatialReference: window.view.spatialReference
      }
      // 计算标注长度
      var namelen = 0
      var nameL = item[options.attr.name].replace(/\s+/g, '')
      for (let m = 0; m < nameL.length; m++) {
        let charCode = nameL.charCodeAt(m)
        if (charCode > 255) {
          namelen += 2
        } else {
          namelen++
        }
      }
      var width = namelen * 0.5 * fontsize + 13
      var height = fontsize * 1.7
      var xoffset = width / 2 + 6
      // 文字符号
      var textSymbol = {
        type: 'text',
        color: '#fff',
        text: item[options.attr.name],
        xoffset: xoffset,
        yoffset: -4,
        font: {
          size: fontsize,
          weight: 'bold'
        }
      }
      // 背景符号
      var path = `M0 0L0 ${height}L${width} ${height}L${width} 0L0 0`
      var backgroundSymbol = {
        type: 'simple-marker',
        path: path,
        color: [46, 130, 255, 0.8], //蓝色
        xoffset: xoffset,
        size: Math.max(width, height) > 191 ? 191 : Math.max(width, height),
        outline: {
          color: [0, 78, 253, 1], //蓝色
          width: 1
        }
      }
      // 标注
      var graphicB = new Graphic({
        geometry: point,
        symbol: backgroundSymbol,
        attributes: item
      })
      var graphicT = new Graphic({
        geometry: point,
        symbol: textSymbol,
        attributes: item
      })
      window.map.findLayerById(options.id).add(graphicB)
      window.map.findLayerById(options.id).add(graphicT)
    }
  })
}

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值