sg-heatmap
Version:
Open-source all-in-one Swiss Army knife tool for creating Choropleth maps
88 lines (74 loc) • 2.87 kB
JavaScript
export default function supportOpenLayers(heatmap) {
function initializeRenderer(colorScale) {
var defaultStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new window.ol.style.Style();
var addonStyle = arguments[2];
if (!window) throw new Error('Method initializeRenderer should only be called browser-side');
if (!window.ol) throw new Error('OpenLayers not loaded');
this.colorScale = colorScale;
var featureCollection = {
type: 'FeatureCollection',
features: this.children.map(function (c) {
return {
id: c.id,
type: 'Feature',
geometry: c.geometry,
properties: Object.assign({}, c.properties, { color: null })
};
})
};
var vectorSource = new window.ol.source.Vector({
features: new window.ol.format.GeoJSON().readFeatures(featureCollection, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
})
});
var styleFunction = function styleFunction(feature) {
var color = feature.get('color');
var style = [defaultStyle];
if (color) {
if (addonStyle) style.push(addonStyle);
style.push(new window.ol.style.Style({ fill: new window.ol.style.Fill({ color: color }) }));
}
return style;
};
if ('renderer' in this) {
console.log('Existing renderer replaced');
this.renderer.setVisible(false);
this.renderer.setSource(vectorSource);
this.renderer.setStyle(styleFunction);
this.renderer.setVisible(true);
} else {
this.renderer = new window.ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
}
return this.renderer;
}
function render(stat) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!this.renderer) throw new Error('Renderer has not been initialized');
var colorScale = options.colorScale || this.colorScale;
var _getStat = this.getStat(stat),
statValues = _getStat.values,
unchanged = _getStat.unchanged,
min = _getStat.min,
max = _getStat.max;
var domain = options.domain || [min, max];
function normalize(value) {
return (value - domain[0]) / (domain[1] - domain[0]);
}
Object.keys(statValues).forEach(function (key) {
var normalized = normalize(statValues[key]);
var transformed = Math.pow(normalized, options.transform || 1);
var color = colorScale(transformed);
_this.renderer.getSource().getFeatureById(key).set('color', color);
});
unchanged.forEach(function (key) {
_this.renderer.getSource().getFeatureById(key).set('color', null);
});
}
heatmap.initializeRenderer = initializeRenderer.bind(heatmap);
heatmap.render = render.bind(heatmap);
}