2

In OpenLayers, when you are giving a style to layer, say a WFS layer, we can give stroke width, like this:

var layerWFS = new ol.layer.Vector({
    source: sourceWFS,
    title: 'plot_layer',
    name: 'plot_layer',
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(255, 0, 255, 1)',
            width: 1
        })
    })
});

Here width is 1 , I would like to know in which dimension that we are giving the stroke width, whether:

  1. millimeter (mm) 1 means 1mm
  2. centimeter (cm) 1 means 1cm

2 Answers 2

2

Style are based on pixels (the screen unit). They are not related to resolution (related to scale). If you want to tie width with scale on the map, you should use a function instead as it can access resolution

var layerWFS = new ol.layer.Vector({
    source: sourceWFS,
    title: 'plot_layer',
    name: 'plot_layer',
    style: function(feature, resolution) {
      // Resolution = number of meters for a pixel (at least for EPSG 3857)
      console.log(resolution);
      return new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(255, 0, 255, 1)',
            width: 1
        })
      })
    }
});
0
0

The resolution provided by OpenLayers is based on cartesian distance, which is very inaccurate for EPSG:3857.

See Pseudo Mercator error?

In your style function, you can use getPointResolution as follows to get a more accurate stroke width.

function myStyle(feature: FeatureLike, resolution: number) {
  const extent = feature.getGeometry().getExtent();

  const pointResolution = getPointResolution('EPSG:3857', resolution, extent);

  return new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(255, 0, 255, 1)',
      width: 1 / pointResolution
    })
  });
}

This should result in much more accurate widths. As this function only calculates the resolution based on 1 point, features spanning entire countries would still be inaccurate, but for viewing purposes on a smaller scale this method would be sufficient.

2
  • 1
    It would be much simpler to use ol.proj.getPointResolution.
    – TomazicM
    Commented Sep 22, 2023 at 9:57
  • Thanks, wasn't aware of that functionality in OL
    – b9s
    Commented Sep 22, 2023 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.