OL3 - Override default select style

by Jonatas Walker

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/ol3/3.10.1/ol.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/ol3/3.10.1/ol.min.css">
<div id="map"></div>

CSS

html,body,#map { width:100%; height:100%; margin:0; }
#map {
    position: absolute;
    z-index: 5;
}
#msg{
    position: absolute;
    z-index: 10;
    left: 50%;
    transform: translate(-50%, 5px);
    background-color: rgba(238,238,238,.6);
    padding: 10px;
    color: #222;
    width: 350px;
    text-align: center;
}

JavaScript

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.MapQuest({layer: 'sat'})
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([10,20]),
        zoom: 4
    })
});

var vectorSource = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: [
        new ol.style.Style({
            stroke: new ol.style.Stroke({
                width: 6,
                color: [40, 40, 40, 1],
                lineDash: [4, 10]
            })
        })
    ]
});
map.addLayer(vectorLayer);

var lineString = new ol.geom.LineString([
    ol.proj.fromLonLat([0, 20]),
    ol.proj.fromLonLat([20, 20])
]);
var trackFeature = new ol.Feature({
    geometry: lineString
});
vectorSource.addFeature(trackFeature);

var select = new ol.interaction.Select();
map.addInteraction(select);

var style_modify = new ol.style.Style({
    stroke: new ol.style.Stroke({
        width: 6,
        color: [123, 160, 52, 1]
    })
});

select.on('select', function(evt){
    var selected = evt.selected;
    var deselected = evt.deselected;
    
    if (selected.length) {
        selected.forEach(function(feature){
            console.info(feature);
            feature.setStyle(style_modify);
        });
    } else {
        deselected.forEach(function(feature){
            console.info(feature);
            feature.setStyle(null);
        });
    }
});