Vector with style

by ahocevar

HTML

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

CSS

#map {
        background-color: gray;
        height: 256px;
        width: 512px;
    }

JavaScript

var source = new ol.source.KML({
    url: 'https://rawgit.com/openlayers/ol3-workshop/master/src/data/layers/buildings.kml',
    extractStyles: false
});
source.on('change', function() {
  var extent = source.getExtent();
  map.getView().fitExtent(extent, map.getSize());
});

var map = new ol.Map({
    target: 'map',
    layers: [
    new ol.layer.Vector({
        title: 'Buildings',
        source: source,
        style: (function () {
            var defaultStyle = [new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'navy'
                }),
                stroke: new ol.style.Stroke({
                    color: 'black',
                    width: 1
                })
            })];
            var ruleStyle = [new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'olive'
                }),
                stroke: new ol.style.Stroke({
                    color: 'black',
                    width: 1
                })
            })];
            var stroke = new ol.style.Stroke({
                color: 'black'
            });
            var textStroke = new ol.style.Stroke({
                color: '#fff',
                width: 3
            });
            var textFill = new ol.style.Fill({
                color: '#000'
            });
            var textStyle = new ol.style.Style({
                stroke: stroke,
                text: new ol.style.Text({
                    font: '12px Calibri,sans-serif',
                    text: '',
                    fill: textFill,
                    stroke: textStroke
                })
            })
            defaultStyle.push(textStyle);
            ruleStyle.push(textStyle);
            return function (feature, resolution) {
                if (resolution < 0.00002) {
                    textStyle.getText().setText(feature.get('key'));
                } else {
                    textStyle.getText().setText('');
               ...