3

I am trying to change the opacity of a multipolygon feature on mouseover. I am able to get the feature on mouseover and change the style but am unable to animate the process of the opacity going from 0.3 to 0.8 for example.

I have read through the docs but cant find anything...

Any clue?

Mike Lammers
  • 542
  • 9
  • 27

1 Answers1

6

A feature won't automatically re-render when the only change is the elapsed time a style function would calculate if it is called, but calling feature.changed() will trigger another render.

  var map = new ol.Map({
  target: document.getElementById('map'),
  view: new ol.View({
      center: ol.proj.fromLonLat([0, 50]),
      zoom: 7,
  })
});

var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature(
        ol.geom.Polygon.fromExtent([-1, 50, 1, 51]).transform('EPSG:4326', map.getView().getProjection())
      )
    ]
  })
});

var selectedStyle = new ol.style.Style({
 stroke: new ol.style.Stroke({
   width: 2,
   color: 'blue'
 }),
 fill: new ol.style.Fill()
});

var start;

map.addLayer(layer);
var select = new ol.interaction.Select({
  condition: ol.events.condition.pointerMove,
  style: function(feature) {
    var elapsed = new Date().getTime() - start;
    var opacity = Math.min(0.3 + elapsed/10000, 0.8);
    selectedStyle.getFill().setColor('rgba(255,0,0,' + opacity + ')');
    feature.changed();
    return selectedStyle;
  }
});
select.on('select', function(){ start = new Date().getTime(); });
map.addInteraction(select);
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet"/>
<div id="map" class="map"></div>
Mike
  • 16,042
  • 2
  • 14
  • 30
  • It works perfectly in your example but cant get it to work in my code... I use webpack and my features are multipolygons, maybe that can be an issue but im not sure. If i put a console log in the "select.on('select')...." i see it in the log but when i put an console log in the Select style function ("style: function(feature)") It doesnt show in the log. Any clue? – Mike Lammers Jun 06 '19 at 08:36
  • 1
    A select style won't override a style set directly on the feature, it only works when a feature uses a layer style. – Mike Jun 06 '19 at 11:20