Skip to content Skip to sidebar Skip to footer

Scaling The Icon-image Size To An Absolute Value

I'm developing an application where one functionality is displaying a device on a map using open-layers. These devices can be added by the user and they all can have a custom icon-

Solution 1:

I suggest you use a style cache indexed by src url (it's more efficient in any situation should resolve the async problem)

var styleCache = {};

var styleFunction = function(feature){
  var device = feature.get("device");
  var icon = (device.familyIds.length > 0 ? icons.find(i => i.familyIds.includes(device.familyIds[0])) : undefined);
  var url = (icon != undefined ? newFunction("device", "familyProperty", icon.iconSource)(device, icon.familyProperty) : './img/icons/icon_default.png');
  var style = styleCache[url];
  if (!style) {
    style = new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 1],
        src: url,
        scale: 0
      }),
      text: new ol.style.Text({
        offsetY: 15,
        font: "20px Calibri,sans-serif"
      })
    });
    var img = newImage();
    img.onload = function() {
      style.getImage().setScale(40/img.width);
      feature.changed();  // force a refresh or just wait until next render?
    }
    img.src = url;
    styleCache[url] = style;
  }
  style.getText().setText(device.name);
  return style;
}

The device name text will need to be set "on demand" as devices might shares images.

Solution 2:

Scale icon if too big in -> image: new ol.style.Icon(....):

scale: 0.4,

Post a Comment for "Scaling The Icon-image Size To An Absolute Value"