javascript - 向标记添加文本(功能)

标签 javascript openlayers openlayers-5

我使用 OpenLayers 5.3 对标记标记进行了一些研究。不幸的是,我没有让文本发挥作用。我将文本插入到要素对象中。带有图像的标记可见并按预期工作,但不显示任何文本。

这是我的代码:

var map;
var view;
var vectorSource;
var vectorLayer;
var ownMarker = null;

function drawMap() {

  var coordinate = [13.4, 52.5077286];
  vectorSource = new ol.source.Vector({});
  vectorLayer = new ol.layer.Vector({
    source: vectorSource
  });
  view = new ol.View({
    center: ol.proj.fromLonLat(coordinate),
    zoom: 12,
    maxZoom: 17,
    minZoom: 7
  });
  map = new ol.Map({
    layers: [new ol.layer.Tile({
      source: new ol.source.OSM()
    }), vectorLayer, ],
    target: document.getElementById('map'),
    controls: ol.control.defaults(),
    view: view
  });

  var marker;
  this.setOwnMarker = function(coordinate) {
    marker = new ol.Feature(
      new ol.geom.Point(ol.proj.fromLonLat(coordinate))
    );
    marker.setStyle(iconRed);
    ownMarker = marker;
    vectorSource.addFeature(marker);
  }

  this.addMarker = function(lon, lat) {
    var mar = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
      text: new ol.style.Text({
        text: "Test text",
        scale: 1.2,
        fill: new ol.style.Fill({
          color: "#fff"
        }),
        stroke: new ol.style.Stroke({
          color: "0",
          width: 3
        })
      })
    });

    var iconBlue = new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [12, 40],
        anchorXUnits: 'pixels',
        anchorYUnits: 'pixels',
        opacity: 1,
        src: '../../images/marker_blue.png'

      })
    });
    mar.setStyle(iconBlue);
    vectorSource.addFeature(mar);
  }
  return this;
}

最佳答案

  this.addMarker = function(lon, lat) {
    var mar = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
    });
    var iconBlue = new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [12, 40],
        anchorXUnits: 'pixels',
        anchorYUnits: 'pixels',
        opacity: 1,
        src: '../../images/marker_blue.png'
      }),
      text: new ol.style.Text({
        text: "Test text",
        scale: 1.2,
        fill: new ol.style.Fill({
          color: "#fff"
        }),
        stroke: new ol.style.Stroke({
          color: "0",
          width: 3
        })
      })
    });
    mar.setStyle(iconBlue);
    vectorSource.addFeature(mar);
  }

关于javascript - 向标记添加文本(功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638476/

相关文章:

javascript - 使图表有效地呈现负值

javascript - Openlayers:如何根据功能选择应使用哪种样式的弹出窗口?

javascript - OpenLayers 2 - 如何获取所选要素(点)的坐标

css - 无法以 Angular 获取 openlayers css

javascript - 如何将许多带有自定义文本的标记添加到 openlayers 5

javascript - 从数据库获取 JavaScript 对象

Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数)

javascript - 通过 Mix 将 node_modules 导入 Laravel

javascript - 当我在 php 中从数据库中检索数据并显示它时如何隐藏显示表中的密码字段

javascript - Open Layers 3 中的组标记。