OpenLayers - Select Interaction Programmatically

by Jonatas Walker

HTML

<link rel="stylesheet" href="https://openlayers.org/en/v3.18.2/css/ol.css">
<script src="https://openlayers.org/en/v3.18.2/build/ol.js"></script>
<div id="map" class="map"></div>

CSS

.map {
  background: grey;
}

JavaScript

var featurePoly = new ol.Feature(new ol.geom.Polygon([[
  [-12550727, 2281352], [-11168471, 3244427],
  [-10867077, 1986886], [-12550727, 2281352]
]]));
var source = new ol.source.Vector({
  features: [featurePoly]
});
var layer = new ol.layer.Vector({
  source: source
});

var collection = new ol.Collection();
var select = new ol.interaction.Select({
	features: collection
});

var map = new ol.Map({
  interactions: ol.interaction.defaults().extend([select]),
  layers: [layer],
  target: 'map',
  view: new ol.View({
    center: [-11407508, 2520388],
    zoom: 2
  })
});

window.setTimeout(function() {
	collection.push(featurePoly);
  //select.dispatchEvent('select');
  select.dispatchEvent({
  	type: 'select',
    selected: [featurePoly],
    deselected: []
  });
}, 2000);

select.on('select', function(evt) {
	console.info(evt.selected[0]);
});