Openlayers 3:为feature添加文本标签

Openlayers 3: add text label to feature

本文关键字:添加 文本标签 feature Openlayers      更新时间:2023-09-26

我有当前设置在这里:全功能小提琴的例子,而我已经设法缩放到每个多边形特征,我也想在每个上显示一个集中的文本标签…get_fields方法中发现的field_title变量。我不知道如何做到这一点,我所有的谷歌已经提出了这篇文章:http://openlayers.org/en/v3.3.0/examples/vector-labels.html我发现完全困惑,因为我是一个小的新OL!

要添加一个文本到ol.Feature中,您将存储描述在特征中,并设置一个样式函数(将从特征中获取描述并显示它):

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') : ''
      })
    })
  ];
}
你小提琴

由于我是新来的,不允许评论,所以我把我的评论作为@andre_ss6问题的新答案。我也会在this上得到Window。对我来说有效的是传递特征对象作为函数的第一个参数:

function styleFunction(feature) {

,然后使用该参数代替this:

text: feature.get('description')