3

I'm using a icon 20x20 pxl to be displayed at the map with below code:

When I zoom the map, the icon appears to be small, how can I change the icon size with map zooming?

 <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
 <script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>

<script>
var baseMapLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
  });

var view = new ol.View({
            center: ol.proj.fromLonLat([-74.0061,40.712]), 
            zoom: 17 //Initial Zoom Level
})

var map = new ol.Map({
    target: 'map',
    layers: [ baseMapLayer],
    view: view
});

// Make a new feature marker
var marker = new ol.Feature({
    name: 'Null Island',
    population: 4000,
    rainfall: 500,
    geometry: new ol.geom.Point(
      ol.proj.fromLonLat([-74.006,40.7127])  // new Point([0, 0])
    ),  // Cordinates of New York's Town Hall
});

// Style the marker
var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(({
        color: '#ffcd46',
        crossOrigin: 'anonymous',
        src: 'http://127.0.0.1:8081/static/img/truck.png'
    }))
});

marker.setStyle(iconStyle);

// Make a source for the feature 
var vectorSource = new ol.source.Vector({
    features: [marker]
});
// Make a new layer
var markerVectorLayer = new ol.layer.Vector({
    source: vectorSource,
});

map.addLayer(markerVectorLayer);
</script>
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203

1 Answers1

11

You could do it with a style function, changing the scale as the resolution changes. Resolution can change a lot so you might want to change scale in inverse proportion square root or cube root of the resolution, experiment to see what suits your application.

If set on the feature the syntax depends on the version of OpenLayers

OpenLayers 4:

marker.setStyle(function(resolution) {
    iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
    return iconStyle;
});

OpenLayers 5:

marker.setStyle(function(feature, resolution) {
    iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
    return iconStyle;
});

Or you can set the style on the layer, where the syntax is the same in both versions

var markerVectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: function(feature, resolution) {
        iconStyle.getImage().setScale(1/Math.pow(resolution, 1/3));
        return iconStyle;
    }
});
Mike
  • 16,042
  • 2
  • 14
  • 30
  • My image was 48x48px, this formula did not quite work - i just multiplied it by 10 (the whole expression and it works fine for my use case) – alext Jul 18 '23 at 18:28