Openlayers 3:为特征添加文本标签

Openlayers 3: add text label to feature

我在此处设置了当前设置:fully functional fiddle example and whilst I have managed to zoom to each polygon feature I would also like to display a centralised text label on each... the field_title variable found within the get_fields method. I have no idea how to do this and all my googling has come up with this article: http://openlayers.org/en/v3.3.0/examples/vector-labels.html 由于我是 OL 的新手,我发现这完全令人困惑!

要向 ol.Feature 添加文本,您需要将描述存储在功能中,set a style that is a style 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.

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

function styleFunction(feature) {

然后使用该参数代替 this:

text: feature.get('description')