[GIS] OpenLayers doesn’t apply style for KML file

kmlopenlayersstyle

I've used OpenLayers 4 to create a simple web map to load a KML file. I made a style for the KML file and also change "extraceStyle" of the layer to false, but it doesn't use my custom style.

var center = ol.proj.transform([51.34, 35.65], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
    center: center,
    zoom: 2
});

// time zones layer style
var tzStyle = new ol.style.Style({
    stroke: new ol.style.Stroke({
        color: '#40c8c8',
        opacity: 0.5
    }),
    text: new ol.style.Text({
        font: '20px Verdana',
        text: 'TZ',
        fill: new ol.style.Fill({
            color: '#404040',
            opacity: 0.75
        })
    })
});

// KML of time zones
var tzSource = new ol.source.Vector({
    extractStyles: false,
    format: new ol.format.KML(),
    url: 'http://localhost:8080/OpenLayersAssets/timezones.kml',
    projection: 'EPSG:3857'
});
var timezones = new ol.layer.Vector({
    source: tzSource,
    style: tzStyle
});

var map = new ol.Map({
    target: 'map',
    layers: [timezones],
    view: view
});

Best Answer

You just need to change the position of the option extractStyles: false. It should be within the new ol.format.KML options instead of new ol.source.Vector options.

So the result would be

var tzSource = new ol.source.Vector({
    format: new ol.format.KML({
      extractStyles: false
    }),
    url: 'timezones.kml',
    projection: 'EPSG:3857'
});
Related Question