形状/标记/无论有什么数据。

时间:2017-10-30 22:51:41

标签: openlayers

我搜索了我知道的每个关键字,但似乎无法找到指导我的示例。我想使用OpenLayers在地图上叠加点,并且这些点将具有不同的数据和背景颜色。

以下是我使用Google Maps API完成的示例。如何使用OpenLayers进行相同的操作?

enter image description here

1 个答案:

答案 0 :(得分:1)

获得价值很容易。只需从样式函数返回ol.style.Style ol.style.Text

var style = new ol.style.Style({
  text: new ol.style.Text({
    text: '' // will be modified dynamically in the style function
  })
});
var layer = new ol.layer.Vector({
  style: function(feature) {
    var value = feature.get('since_midnight');
    style.getText().setText(value);
    return style;
  }
});

背景有点棘手,但在实现https://github.com/openlayers/openlayers/issues/4577#issuecomment-328968055时,近距离功能会更容易。目前,可以使用自定义渲染器创建背景。执行此操作时,您还可以在自定义渲染器中渲染文本,而不需要ol.style.Text:

var style = new ol.style.Style({
  renderer: function(coordinates, state) {
var context = state.context;
    context.font = (state.pixelRatio * 12) + 'px Arial,Helvetica,sans-serif';
    var magnitude = parseFloat(parseFloat(state.feature.get('name').split(' ')[1]));
    var width = context.measureText(magnitude).width + 10;
    var height = 16 * state.pixelRatio;
    context.save();

    if (magnitude < 5.2) {
      context.fillStyle = 'green';
    } else if (magnitude >= 5.2 && magnitude < 5.8) {
      context.fillStyle = 'orange';
    } else {
      context.fillStyle = 'red';
    }
    context.fillRect(
      coordinates[0] - width / 2,
      coordinates[1] - height / 2,
      width,
      height
    );
    context.strokeStyle = 'white';
    context.strokeRect(
      coordinates[0] - width / 2,
      coordinates[1] - height / 2,
      width,
      height
    );
    context.fillStyle = 'white';
    context.strokeStyle = 'black';
    context.lineWidth = 2;
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.strokeText(magnitude, coordinates[0], coordinates[1]);
    context.fillText(magnitude, coordinates[0], coordinates[1]);
    context.restore();
  }
});
var layer = new ol.layer.Vector({
  style: style,
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v4.4.2/examples/data/kml/2012_Earthquakes_Mag5.kml',
    format: new ol.format.KML({
      extractStyles: false
    })
  })
});
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    layer
  ],
  target: 'map',
  view: new ol.View({
    zoom: 2,
    center: [0, 0]
  })
})
#map {
  width: 100%;
  height: 100%;
  margin: 0;
}
<link href="https://openlayers.org/en/v4.4.2/css/ol.css" rel="stylesheet" />
<script src="https://openlayers.org/en/v4.4.2/build/ol.js"></script>
<div id="map"></div>