OpenLayers 3 Image and Text style zindex

2019-09-02 08:54发布

问题:

I've noticed that text and image styles don't seem to respect their layer order when being rendered. For example, when many features with these styles are close together, all the text is rendered on top of other overlapping vector features. Is there a way to disable or override this behavior? Thanks.

myFeature.setStyle(new ol.style.Style({
  image: new ol.style.Icon({
    src: '/images/myImage.png',
    anchor: [0.5, 1],
    anchorXUnits: 'fraction',
    anchorYUnits: 'fraction'
  })
}));

myOtherFeature.setStyle(new ol.style.Style({
  image: new ol.style.Circle({
    fill: new ol.style.Fill({
      color: 'rgb(255,200,77)'
    }),
    stroke: new ol.style.Stroke({
      color: 'rgba(0,0,0,.2)',
      width: 1
    }),
    radius: 14
  }),
  text: new ol.style.Text({
    font: 'light 10px Arial',
    text: '1',
    fill: new ol.style.Fill({color: 'black'}),
    stroke: new ol.style.Stroke({color: 'black', width: 0.5})
  })
}));

回答1:

When stacking point symbols with text, you need to give every point its own (increasing) zIndex if you want the text to stick to the symbol. See http://jsfiddle.net/8g1vayvc/. You can also do that in a style function:

var myStyle = new ol.style.Style({/*...*/});
var zIndex = 0;
function styleFunction(feature, resolution) {
  myStyle.setZIndex(zIndex++);
  return myStyle;
}