javascript - OpenLayers 3 中的自定义矢量形状标记

标签 javascript vector openlayers-3

我有一张 OpenLayers 3 map ,上面显示了各种数据。其中一幅展示了附近雷达探测到的船只。目前我将船显示为一个简单的矢量圆。我想将其显示为船形矢量。

据我所知,我最好的选择是使用 *.png 图标,并执行如下操作:

style: new ol.style.Icon({
  image: new ol.style.Icon(({
    anchor: [0.5, 0.5],
    anchorXUnits: 'fraction',
    anchorYUnits: 'fraction',
    opacity: 1,
    scale: 1,
    src: '/Content/images/boat.png',
    rotation: 0
  }))
});

这可行,但我希望有一个在放大/缩小时不缩放的矢量。我目前针对某些不同数据的解决方案是显示一个矩形,但它在缩放时会缩放:

var style = (function () {
  function (feature, resolution) {
  // font size
  if (resolution > 0.4) var fontSize = '12px';
  else var fontSize = '14px';

  var temperature = feature.get('temperature') || '-';
  temperature = temperature.replace(/,/g, '.');

  return [new ol.style.Style({
    fill: fill,
    stroke: stroke,
    text: new ol.style.Text({
      font: 'bold ' + fontSize + ' helvetica,sans-serif',
      text: Math.round(temperature * 100) / 100 + '°C',
      fill: new ol.style.Fill({ color: '#000' })
    }),
    geometry: function (feature) {
      var startingCoordinates = feature.getGeometry().getCoordinates();
      var coordinates = [[
          [startingCoordinates[0] + 0, startingCoordinates[1] + 0],
          [startingCoordinates[0] + 33, startingCoordinates[1] + 0],
          [startingCoordinates[0] + 33, startingCoordinates[1] + (-11.35)],
          [startingCoordinates[0] + 0, startingCoordinates[1] + (-11.35)],
          [startingCoordinates[0] + 0, startingCoordinates[1] + 0]
      ]];

      return new ol.geom.Polygon(coordinates);
      }
    })]
  }
})()

有没有比使用 startingCoordinates + (constant * resolution) 更好的解决方案?使用矢量与使用 png 有什么显着的性能差异吗?谢谢

编辑: 在咨询了我的几位同事之后,我基本上是想拥有这个 http://openlayers.org/en/v3.5.0/examples/regularshape.html但具有自定义形状。

EDIT2:其实更像这样http://dev.openlayers.org/examples/graphic-name.html '命名符号“闪电”、“矩形”和“教堂”是用户定义的。'

最佳答案

我知道这是一个老问题,但我会为其他人回答,因为这是我在研究如何做到这一点时的最佳结果。

我的解决方案是使用带有 svg 的 data:image/svg+xml 来提供可以以编程方式生成的图标

new ol.style.Style({
    image: new ol.style.Icon({
        // svg of an equilateral triangle 25px wide at the base
        src: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="21.65" width="25" id="canvas"><polygon points="0,0 25,0 12.5,21.65" style="fill:rgba(0,0,0,1);"></polygon></svg>')}`,
    }),
})

注:你don't need to base64在数据 url 中对 svg 进行编码,但对于非 webkit 浏览器,您确实需要对其进行 encodeURIComponent()。

关于javascript - OpenLayers 3 中的自定义矢量形状标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30255779/

相关文章:

c++ - 在类里面使用模板的困惑

javascript - 如何在 OpenLayers3 中将图 block 层居中

JavaScript 严格模式 - 扩展 jQuery 小部件的属性时为 "this is undefined"

javascript - 无法使用javascript函数更改图像位置

javascript - 仅当ajax响应时间超过X毫秒时,如何调用 "Please Wait"窗口?

javascript - AppendChild (Javascript) 和 Internet Explorer

c++ - 在结构 vector 中初始化一个 vector

C++ std::vector<uint8> 已填充,但未显示数据

openlayers-3 - 如何在 OpenLayers 3 上添加标记给出坐标

javascript - 带有 OpenLayers 的 InfoWindows