Saturday, 8 February 2020

How to set the URL from an icon in OpenLayers 3?


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?



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...