【问题标题】:Openlayers 3: add text label to featureOpenlayers 3:为特征添加文本标签
【发布时间】:2016-08-17 21:31:35
【问题描述】:

我在这里设置了当前设置:fully functional fiddle example,虽然我已经设法缩放到每个多边形特征,但我还想在每个特征上显示一个集中的文本标签...field_title 变量在 @987654324 中找到@ 方法。我不知道如何做到这一点,我所有的谷歌搜索都得出了这篇文章:http://openlayers.org/en/v3.3.0/examples/vector-labels.html,我觉得这完全令人困惑,因为我对 OL 有点陌生!

【问题讨论】:

  • 你能把动画部分移到另一个问题吗?它可以帮助解决最初的困惑。
  • @JonatasWalker 已经完成了。谢谢。

标签: javascript openlayers-3


【解决方案1】:

要向ol.Feature 添加文本,您需要将描述存储在功能中,set a stylestyle function(将从功能中获取描述并显示它):

field_polygon.set('description', field_title);
field_polygon.setStyle(styleFunction);

function styleFunction() {
  return [
    new ol.style.Style({
        fill: new ol.style.Fill({
        color: 'rgba(255,255,255,0.4)'
      }),
      stroke: new ol.style.Stroke({
        color: '#3399CC',
        width: 1.25
      }),
      text: new ol.style.Text({
        font: '12px Calibri,sans-serif',
        fill: new ol.style.Fill({ color: '#000' }),
        stroke: new ol.style.Stroke({
          color: '#fff', width: 2
        }),
        // get the text from the feature - `this` is ol.Feature
        // and show only under certain resolution
        text: map.getView().getZoom() > 12 ? this.get('description') : ''
      })
    })
  ];
}

Your fiddle.

【讨论】:

  • 这太棒了!谢谢!我如何只显示高于某个缩放级别的文本?
  • 查看更新的答案。 map.getView().getZoom() > 12 ? this.get('description') : ''
  • 你确定这行得通吗?我在this 上得到Window 而不是ol.Feature
  • 我没有引用map,所以我最好为styleFunction 使用不同的签名:const styleFunction = (myParams) => (feature, resulution) => . . . 然后我比较resolutionvariable 而不是getZoom() 来更改文本内容
【解决方案2】:

由于我是新来的,不允许发表评论,所以我将我的评论作为对@andre_ss6 问题的新答案。我还在this 上收到Window。对我有用的是将特征对象作为函数的第一个参数传递:

function styleFunction(feature) {

然后使用该参数代替this:

text: feature.get('description')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多