2

I've tried to set the URL from an icon but without success. In fact, I've been searching in OpenLayers API but I haven't seen any method to set it. In OpenLayers 2 I've seen that It's possible.

I want to be able to change the URL at any time.

Do you have any idea?

1 Answer 1

2

To answer your question, now that I understand it, there is no way to set the src of an icon after instantiation. My guess would be because the creation of a style.Icon object is tied in to the image cache somehow. The developers obviously thought not to duplicate that logic: https://github.com/openlayers/ol3/blob/v3.7.0/src/ol/style/iconstyle.js#L589

This example here shows you how to create an icon by referencing an image file. Note the data/icon.png specified in the icon configuration is relative and resolves to http://openlayers.org/en/v3.7.0/examples/data/icon.png. You could either use an absolute or relative url depending on what you need.

var iconStyle = new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: 'data/icon.png'
  }))
});

As with all other style types in OpenLayers, it is better to create a cache of styles instead of one style per feature. An example on how to do this would be roughly as follows:

var styleCache = [];

for (var i = 0; i < dataSet.length; i++) {
    var data = dataSet[i];
    var style;
    if (styleCache[data.styleAttribute]) {
       styleCache[data.styleAttribute] = new ol.style.Style({ 
            image: new ol.style.Icon({ etc.. }) 
       });
    }
    style = styleCache[data.styleAttribute];
    var feature = new ol.Feature({  etc..  });
    feature.setStyle(feature);
}

If you need to change the style on the fly, you would just reference one of the styles in the style cache, or add a new style to the cache, then reference it. On an existing feature you can change the style using feature.setStyle(iconStyle).

I hope this helps.

4
  • That is my question... I've been in OpenLayer 3 API and I can't to set Image source URI because there isn't a method to set it... I can be to able to set the fill, text, etc... I'm not sure if there is another method to do it. Aug 6, 2015 at 4:04
  • What's stopping you from creating a new instance of the Icon type each time you need a new one?
    – nagytech
    Aug 6, 2015 at 4:17
  • I have a layer where there are multiple type of different features, So... I'd like to differentiate between each one... That's is all. Do you have any example? Aug 6, 2015 at 4:22
  • I think I see where you're headed with this, not sure if my edits will help...
    – nagytech
    Aug 6, 2015 at 4:45

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.