Interactive interface for browsing global, full-resolution satellite imagery
Add initial vector layer support - Rename rerenderPaletteSelector to renderColorPaletteSelector - Import vector dependencies for creating vector layers - Check for vector type and create vector layer with base styling - Add ability to click on vector point to show it's attributes in the console - Add color conversion utilities - Add check for mapbox-gl-style metadata type on build
ZachTRiceb54a18ebb0fc
diff --git a/doc/configuration.md b/doc/configuration.mdindex 42b132491..f8230267a 100644--- a/doc/configuration.md+++ b/doc/configuration.md@@ -63,7 +63,7 @@ The minimum set of required properties are as follows:The following properties are required if this information is not available via the GIBS WMTS GetCapabilities document:-- **type**: Tile service type, either *wmts* or *wms*.+- **type**: Tile service type, either *wmts*, *wms*, or *vector*.- **format**: Image format type, either *image/png* or *image/jpeg*.- **tileSize**: For WMS layers only, an array of pixel dimensions used to tile the requests. For example, *[512, 512]*- **period**: Use *subdaily*, *daily*, *monthly*, or *yearly* for layers that have new content and no startDate defined in GetCapabilities. Changing the period will affect how often the layer is requested in the timeline. Use *static* to clear the startDate and always have the layer shown on the timeline.diff --git a/tasks/buildOptions.sh b/tasks/buildOptions.shindex 0c97bf030..814340555 100755--- a/tasks/buildOptions.sh+++ b/tasks/buildOptions.sh@@ -54,6 +54,7 @@ fimkdir -p "$DEST_DIR/config"mkdir -p "$BUILD_DIR/colormaps"+mkdir -p "$BUILD_DIR/vectorstyles"if [ -e "$BUILD_DIR/features.json" ] ; thencp "$BUILD_DIR/features.json" "$BUILD_DIR/config/wv.json/_features.json"@@ -62,7 +63,18 @@ fi# Run extractConfigFromWMTS.py script with config.jsonif [ -e "$BUILD_DIR/config.json" ] ; then"$TASKS_DIR/extractConfigFromWMTS.py" "$BUILD_DIR/config.json" "$BUILD_DIR/gc" \- "$BUILD_DIR/config/wv.json/_wmts" "$BUILD_DIR/colormaps"+ "$BUILD_DIR/config/wv.json/_wmts"+fi++# Run processVectorStyles.py and move colormaps where we want them+if [ -e "$BUILD_DIR/vectorstyles" ] ; then+ mkdir -p "$BUILD_DIR"/config/vectorstyles+ if [ -d "$BUILD_DIR"/gc/vectorstyles ] ; then+ cp -r "$BUILD_DIR"/gc/vectorstyles "$BUILD_DIR"/vectorstyles/gc+ fi+ "$TASKS_DIR/processVectorStyles.py" "$OPT_DIR/$OPT_SUBDIR/config.json" \+ "$BUILD_DIR/vectorstyles" \+ "$BUILD_DIR/config/vectorstyles"fi# Run processColormap.py and move colormaps where we want themdiff --git a/tasks/extractConfigFromWMTS.py b/tasks/extractConfigFromWMTS.pyindex 1f9391384..96c38ea17 100755--- a/tasks/extractConfigFromWMTS.py+++ b/tasks/extractConfigFromWMTS.py@@ -1,13 +1,10 @@#!/usr/bin/env python-from datetime import datetime, date, timedeltaimport jsonfrom optparse import OptionParserimport osimport sys-import urllib2 as urllibimport xmltodict-import isodatefrom processTemporalLayer import process_temporalfrom collections import OrderedDict@@ -18,24 +15,23 @@ help_description = """\Extracts configuration information from a WMTS GetCapabilities file."""-parser = OptionParser(usage="Usage: %s <config_file> <input_dir> <output_dir> <colormaps_dir>" % prog,+parser = OptionParser(usage="Usage: %s <config_file> <input_dir> <output_dir>" % prog,version="%s version %s" % (prog, version),epilog=help_description)(options, args) = parser.parse_args()-if len(args) != 4:+if len(args) != 3:parser.error("Invalid number of arguments")config_file = args[0]input_dir = args[1]output_dir = args[2]-colormaps_dir = args[3]with open(config_file) as fp:config = json.load(fp)tolerant = config.get("tolerant", False)-if not "wv-options-wmts" in config:+if "wv-options-wmts" not in config:sys.exit(0)if not os.path.exists(output_dir):@@ -55,9 +51,11 @@ json_options = {}json_options["indent"] = 4json_options["separators"] = (',', ': ')+class SkipException(Exception):pass+def process_layer(gc_layer, wv_layers, colormaps):id = gc_layer["ows:Identifier"]if id in skip:@@ -101,10 +99,19 @@ def process_layer(gc_layer, wv_layers, colormaps):colormap_link = item["@xlink:href"]colormap_file = os.path.basename(colormap_link)colormap_id = os.path.splitext(colormap_file)[0]- wv_layer["palette"] = {+ wv_layer["vectorStyle"] = {"id": colormap_id}+ elif schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/mapbox-gl-style/1.0":+ colormap_link = item["@xlink:href"]+ colormap_file = os.path.basename(colormap_link)+ colormap_id = os.path.splitext(colormap_file)[0]+ wv_layer["vectorStyle"] = {+ "id": colormap_id+ }++def process_entry(entry, colormaps):layer_count = 0warning_count = 0diff --git a/tasks/getCapabilities.py b/tasks/getCapabilities.pyindex 2c864c032..1b52e946a 100755--- a/tasks/getCapabilities.py+++ b/tasks/getCapabilities.py@@ -28,7 +28,9 @@ if len(args) != 2:config_file = args[0]output_dir = args[1]colormaps = {}+vectorstyles = {}colormaps_dir = os.path.join(output_dir, "colormaps")+vectorstyles_dir = os.path.join(output_dir, "vectorstyles")remote_count = 0error_count = 0warning_count = 0@@ -52,7 +54,6 @@ def process_layer(layer):schema_version = item["@xlink:role"]if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/colormap/1.3":colormap_link = item["@xlink:href"]- #colormap_link = layer["ows:Metadata"]["@xlink:href"]colormap_file = os.path.basename(colormap_link)colormap_id = os.path.splitext(colormap_file)[0]colormaps[colormap_id] = colormap_link@@ -75,16 +76,28 @@ def process_remote(entry):returntry:- if(type(gc["Capabilities"]["Contents"]["Layer"]) is OrderedDict):- process_layer(gc["Capabilities"]["Contents"]["Layer"])- else:- for layer in gc["Capabilities"]["Contents"]["Layer"]:- process_layer(layer)+ for layer in gc["Capabilities"]["Contents"]["Layer"]:+ ident = layer["ows:Identifier"]+ if "ows:Metadata" in layer:+ if ident in config.get("skipPalettes", []):+ sys.stderr.write("%s: WARN: Skipping palette for %s\n" %+ prog, ident)+ global warning_count+ warning_count += 1+ else:+ for item in layer["ows:Metadata"]:+ schema_version = item["@xlink:role"]+ if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/colormap/1.3":+ colormap_link = item["@xlink:href"]+ colormap_file = os.path.basename(colormap_link)+ colormap_id = os.path.splitext(colormap_file)[0]+ colormaps[colormap_id] = colormap_linkexcept Exception as e:print('error: %s: %s' % (url, str(e)))print(str(traceback.format_exc()))+# Fetch every colormap from the API and write response to file systemdef process_colormaps():print "%s: Fetching %d colormaps" % (prog, len(colormaps))@@ -95,7 +108,8 @@ def process_colormaps():try:response = urllib.urlopen(link)contents = response.read()- output_file = os.path.join(colormaps_dir, os.path.basename(link))+ if link.endswith('.xml'):+ output_file = os.path.join(colormaps_dir, os.path.basename(link))with open(output_file, "w") as fp:fp.write(contents)except Exception as e:@@ -105,6 +119,29 @@ def process_colormaps():warning_count += 1print "%s: Fetching %d colormaps" % (prog, len(colormaps))++# Fetch every colormap from the API and write response to file system+def process_vectorstyles():+ print "%s: Fetching %d vectorstyles" % (prog, len(vectorstyles))+ sys.stdout.flush()+ if not os.path.exists(vectorstyles_dir):+ os.makedirs(vectorstyles_dir)+ for link in vectorstyles.values():+ try:+ response = urllib.urlopen(link)+ contents = response.read()+ if link.endswith('.json'):+ output_file = os.path.join(vectorstyles_dir, os.path.basename(link))+ with open(output_file, "w") as fp:+ fp.write(contents)+ except Exception as e:+ sys.stderr.write("%s: WARN: Unable to fetch %s: %s" %+ (prog, link, str(e)))+ global warning_count+ warning_count += 1+ print "%s: Fetching %d vectorstyles_dir" % (prog, len(vectorstyles_dir))++tolerant = config.get("tolerant", False)if "wv-options-fetch" in config:for entry in config["wv-options-fetch"]:@@ -120,6 +157,8 @@ if "wv-options-fetch" in config:sys.stderr.write("%s: ERROR: %s\n" % (prog, str(e)))if colormaps:process_colormaps()+ if vectorstyles:+ process_vectorstyles()print "%s: %d error(s), %d remote(s)" % (prog, error_count, remote_count)diff --git a/tasks/processColormap.py b/tasks/processColormap.pyindex a2fd4b8b7..7b4504add 100755--- a/tasks/processColormap.py+++ b/tasks/processColormap.py@@ -14,7 +14,7 @@ help_description = """\Converts colormaps to JSON files"""-parser = OptionParser(usage="Usage: %s <config_file> <input_dir> <output_dir>" % prog,+parser = OptionParser(usage="Usage: %s <config_file> <colormap_input_dir> <output_dir>" % prog,version="%s version %s" % (prog, version),epilog=help_description)@@ -23,7 +23,7 @@ if len(args) != 3:parser.error("Invalid number of arguments")config_file = args[0]-input_dir = args[1]+colormap_input_dir = args[1]output_dir = args[2]with open(config_file) as fp:@@ -231,7 +231,7 @@ def process_file(file):file_count = 0error_count = 0-for root, dirs, files in os.walk(input_dir):+for root, dirs, files in os.walk(colormap_input_dir):for file in files:try:file_count += 1diff --git a/tasks/processVectorStyles.py b/tasks/processVectorStyles.pynew file mode 100644index 000000000..4907ee6c5--- /dev/null+++ b/tasks/processVectorStyles.py@@ -0,0 +1,59 @@+#!/usr/bin/env python++from optparse import OptionParser+import os+import sys+import json+import shutil++prog = os.path.basename(__file__)+base_dir = os.path.join(os.path.dirname(__file__), "..")+version = "3.0.0"+help_description = """\+Converts colormaps to JSON files+"""++parser = OptionParser(usage="Usage: %s <config_file> <vectorstyles_input_dir> <output_dir>" % prog,+ version="%s version %s" % (prog, version),+ epilog=help_description)++(options, args) = parser.parse_args()+if len(args) != 3:+ parser.error("Invalid number of arguments")++config_file = args[0]+vectorstyles_input_dir = args[1]+output_dir = args[2]++with open(config_file) as fp:+ config = json.load(fp)+skips = config.get("skipPalettes", [])++def copy_file(file):+ input_file = os.path.join(root, file)+ id = os.path.splitext(os.path.basename(input_file))[0]+ if id in skips:+ sys.stderr.write("%s: WARN: [%s] %s\n" % (prog, input_file,+ "Skipping"))+ return++ if input_file.endswith('.json'):+ shutil.copy(input_file, output_dir)++# Main+file_count = 0+error_count = 0++for root, dirs, files in os.walk(vectorstyles_input_dir):+ for file in files:+ try:+ file_count += 1+ copy_file(file)+ except Exception as e:+ sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))+ error_count += 1++print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)++if error_count > 0:+ sys.exit(1)diff --git a/tasks/validateOptions.py b/tasks/validateOptions.pyindex 6c686f8cb..ef98765d4 100755--- a/tasks/validateOptions.py+++ b/tasks/validateOptions.py@@ -99,6 +99,14 @@ for layer_id in wv["layers"].keys():palette_id + ".json")):error("[%s] Unknown palette: %s" % (layer_id, palette_id))del layer["palette"]+ if "vectorStyle" in layer and "id" not in layer["vectorStyle"]:+ error("[%s] No vectorStyle definition" % (layer_id))+ elif "vectorStyle" in layer:+ vector_style_id = layer["vectorStyle"]["id"]+ if not os.path.exists(os.path.join(config_dir, "vectorstyles",+ vector_style_id + ".json")):+ error("[%s] Unknown vector style: %s" % (layer_id, vector_style_id))+ del layer["vectorStyle"]if "group" not in layer and opt.get("warnOnUnexpectedLayer"):error("[%s] Possible unexpected layer, no group defined" % layer_id)remove_layer(wv, layer_id)diff --git a/web/images/direction_arrow.png b/web/images/direction_arrow.pngnew file mode 100644index 000000000..8a8b13e8cBinary files /dev/null and b/web/images/direction_arrow.png differdiff --git a/web/js/debug.js b/web/js/debug.jsindex 54c4a059a..8743854fa 100644--- a/web/js/debug.js+++ b/web/js/debug.js@@ -249,7 +249,7 @@ export function debugLayers(ui, models, config) {}selectedLayer = layerId;if (type === 'palettes') {- palettes.loadRendered(config, layerId)+ palettes.loadRenderedPalette(config, layerId).done(function () {var layer = config.layers[layerId];var palette = config.palettes.rendered[layerId];diff --git a/web/js/layers/options.js b/web/js/layers/options.jsindex 1b1829ea5..a47ac280d 100644--- a/web/js/layers/options.js+++ b/web/js/layers/options.js@@ -39,7 +39,6 @@ export function layersOptions(config, models, layer) {.attr('id', 'wv-layers-options-dialog').attr('data-layer', layer.id);renderOpacity($dialog);-if (config.features.customPalettes) {if (models.palettes.allowed(layer.id) &&(models.palettes.getLegends(layer.id)@@ -49,16 +48,18 @@ export function layersOptions(config, models, layer) {renderLegendButtons($dialog);} */var legend = models.palettes.getLegend(layer.id, index);- if ((legend.type === 'continuous') ||- (legend.type === 'discrete')) {- renderRange($dialog);- if (config.layers[layer.id].type !== 'wms') {- renderPaletteSelector($dialog);- }- } else if (models.palettes.getDefaultLegend(layer.id, index)- .colors.length === 1) {- if (config.layers[layer.id].type !== 'wms') {- renderPaletteSelector($dialog);+ if (legend) {+ if ((legend.type === 'continuous') ||+ (legend.type === 'discrete')) {+ renderRange($dialog);+ if (config.layers[layer.id].type !== 'wms') {+ renderPaletteSelector($dialog);+ }+ } else if (models.palettes.getDefaultLegend(layer.id, index)+ .colors.length === 1) {+ if (config.layers[layer.id].type !== 'wms') {+ renderPaletteSelector($dialog);+ }}}}@@ -293,12 +294,11 @@ export function layersOptions(config, models, layer) {.attr('id', 'wv-palette-selector');$dialog.append($header).append($pane);- rerenderPaletteSelector(true);+ renderColorPaletteSelector(true);};- var rerenderPaletteSelector = function (firstTime) {- var $pane = $('#wv-palette-selector')- .empty();+ var renderColorPaletteSelector = function(firstTime) {+ var $pane = $('#wv-palette-selector').empty();$pane.append(defaultLegend());var recommended = layer.palette.recommended || [];lodashEach(recommended, function (id) {@@ -427,7 +427,7 @@ export function layersOptions(config, models, layer) {var customLegend = function (id) {var source = models.palettes.getDefaultLegend(layer.id, index);- var target = models.palettes.getCustom(id);+ var target = models.palettes.getCustomPalette(id);var targetType = (target.colors.length === 1) ? 'classification' : 'continuous';if ((source.type === 'continuous' && targetType === 'continuous') ||diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.jsindex 9cb43f61e..89b701aef 100644--- a/web/js/map/layerbuilder.js+++ b/web/js/map/layerbuilder.js@@ -5,6 +5,9 @@ import OlSourceTileWMS from 'ol/source/tilewms';import OlLayerGroup from 'ol/layer/group';import OlLayerTile from 'ol/layer/tile';import OlTileGridTileGrid from 'ol/tilegrid/tilegrid';+import MVT from 'ol/format/mvt';+import LayerVectorTile from 'ol/layer/vectortile';+import SourceVectorTile from 'ol/source/vectortile';import lodashCloneDeep from 'lodash/cloneDeep';import lodashMerge from 'lodash/merge';import lodashEach from 'lodash/each';@@ -32,7 +35,6 @@ export function mapLayerBuilder(models, config, cache, Parent) {*/self.createLayer = function (def, options) {var date, key, proj, layer, layerNext, layerPrior, attributes;-options = options || {};date = self.closestDate(def, options);key = self.layerKey(def, options, date);@@ -59,6 +61,20 @@ export function mapLayerBuilder(models, config, cache, Parent) {layerPrior.wv = attributes;layerNext.wv = attributes;+ layer = new OlLayerGroup({+ layers: [layer, layerNext, layerPrior]+ });+ }+ } else if (def.type === 'vector') {+ layer = createLayerVector(def, options, null);+ if (proj.id === 'geographic' && def.wrapadjacentdays === true) {+ layerNext = createLayerVector(def, options, 1);+ layerPrior = createLayerVector(def, options, -1);++ layer.wv = attributes;+ layerPrior.wv = attributes;+ layerNext.wv = attributes;+layer = new OlLayerGroup({layers: [layer, layerNext, layerPrior]});@@ -166,7 +182,7 @@ export function mapLayerBuilder(models, config, cache, Parent) {* @returns {object} OpenLayers WMTS layer*/var createLayerWMTS = function (def, options, day) {- var proj, source, matrixSet, matrixIds, extra,+ var proj, source, matrixSet, matrixIds, urlParameters,date, extent, start;proj = models.proj.selected;source = config.sources[def.source];@@ -188,8 +204,6 @@ export function mapLayerBuilder(models, config, cache, Parent) {matrixIds = def.matrixIds;}- extra = '';-if (day) {if (day === 1) {extent = [-250, -90, -180, 90];@@ -200,14 +214,17 @@ export function mapLayerBuilder(models, config, cache, Parent) {}}- date = options.date || models.date.selected;- if (day) {- date = util.dateAdd(date, 'day', day);+ urlParameters = '?';+ if (def.period === 'daily') {+ date = options.date || models.date.selected;+ if (day) {+ date = util.dateAdd(date, 'day', day);+ }+ urlParameters = '&TIME=' + util.toISOStringDate(date);}- extra = '?TIME=' + util.toISOStringSeconds(util.roundTimeOneMinute(date));var sourceOptions = {- url: source.url + extra,+ url: source.url + urlParameters,layer: def.layer || def.id,cacheSize: 4096,crossOrigin: 'anonymous',@@ -232,6 +249,98 @@ export function mapLayerBuilder(models, config, cache, Parent) {extent: extent,source: new OlSourceWMTS(sourceOptions)});++ return layer;+ };++ /*+ * Create a new Vector Layer+ *+ * @method createLayerVector+ * @static+ *+ * @param {object} def - Layer Specs+ *+ * @param {object} options - Layer options+ *+ *+ * @returns {object} OpenLayers Vector layer+ */+ var createLayerVector = function(def, options, day) {+ var date, urlParameters, proj, extent, source, matrixSet, matrixIds, start;+ proj = models.proj.selected;+ source = config.sources[def.source];+ extent = proj.maxExtent;+ start = [proj.maxExtent[0], proj.maxExtent[3]];++ if (!source) { throw new Error(def.id + ': Invalid source: ' + def.source); }+ if (!source) {+ throw new Error(def.id + ': Invalid source: ' + def.source);+ }+ matrixSet = source.matrixSets[def.matrixSet];+ if (!matrixSet) {+ throw new Error(def.id + ': Undefined matrix set: ' + def.matrixSet);+ }+ if (typeof def.matrixIds === 'undefined') {+ matrixIds = [];+ lodashEach(matrixSet.resolutions, function(resolution, index) {+ matrixIds.push(index);+ });+ } else {+ matrixIds = def.matrixIds;+ }++ if (day) {+ if (day === 1) {+ extent = [-250, -90, -180, 90];+ start = [-540, 90];+ } else {+ extent = [180, -90, 250, 90];+ start = [180, 90];+ }+ }++ var layerName = def.layer || def.id;+ var tms = def.matrixSet;++ urlParameters = '?' ++ '&layer=' + layerName ++ '&tilematrixset=' + tms ++ '&Service=WMTS' ++ '&Request=GetTile' ++ '&Version=1.0.0' ++ '&FORMAT=application%2Fvnd.mapbox-vector-tile' ++ '&TileMatrix={z}&TileCol={x}&TileRow={y}';++ if (def.period === 'daily') {+ date = options.date || models.date.selected;+ if (day) {+ date = util.dateAdd(date, 'day', day);+ }+ urlParameters += '&TIME=' + util.toISOStringDate(date);+ }++ var sourceOptions = new SourceVectorTile({+ url: source.url + urlParameters,+ layer: layerName,+ crossOrigin: 'anonymous',+ format: new MVT(),+ matrixSet: tms,+ tileGrid: new OlTileGridTileGrid({+ extent: extent,+ origin: start,+ resolutions: matrixSet.resolutions,+ tileSize: matrixSet.tileSize+ })+ });++ var layer = new LayerVectorTile({+ renderMode: 'image',+ preload: 1,+ extent: extent,+ source: sourceOptions+ });+return layer;};@@ -249,7 +358,7 @@ export function mapLayerBuilder(models, config, cache, Parent) {* @returns {object} OpenLayers WMS layer*/var createLayerWMS = function (def, options, day) {- var proj, source, extra, transparent,+ var proj, source, urlParameters, transparent,date, extent, start, res, parameters;proj = models.proj.selected;source = config.sources[def.source];@@ -280,16 +389,17 @@ export function mapLayerBuilder(models, config, cache, Parent) {};if (def.styles) { parameters.STYLES = def.styles; }- extra = '';+ urlParameters = '?';- date = options.date || models.date.selected;- if (day) {- date = util.dateAdd(date, 'day', day);+ if (def.period === 'daily') {+ date = options.date || models.date.selected;+ if (day) {+ date = util.dateAdd(date, 'day', day);+ }+ urlParameters += 'TIME=' + util.toISOStringDate(date);}- extra = '?TIME=' + util.toISOStringSeconds(util.roundTimeOneMinute(date));-var sourceOptions = {- url: source.url + extra,+ url: source.url + urlParameters,cacheSize: 4096,wrapX: true,style: 'default',diff --git a/web/js/map/ui.js b/web/js/map/ui.jsindex 280eecf3b..3a3b30fe2 100644--- a/web/js/map/ui.js+++ b/web/js/map/ui.js@@ -641,6 +641,13 @@ export function mapui(models, config) {self.mapIsbeingZoomed = false;}, 200);});++ // TEST: Clicking on a vector shows it's attributes in console.+ map.on('click', function (e) {+ map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {+ console.log(feature.getProperties());+ });+ });return map;};/*diff --git a/web/js/palettes/legend.js b/web/js/palettes/legend.jsindex 63c624f89..cee09c8d4 100644--- a/web/js/palettes/legend.js+++ b/web/js/palettes/legend.js@@ -22,7 +22,7 @@ export function palettesLegend(spec) {loaded = true;render();} else {- palettes.loadRendered(config, layer.id)+ palettes.loadRenderedPalette(config, layer.id).done(function () {if (!loaded) {loaded = true;diff --git a/web/js/palettes/model.js b/web/js/palettes/model.jsindex 8bc6549cb..e63774fb8 100644--- a/web/js/palettes/model.js+++ b/web/js/palettes/model.js@@ -13,20 +13,37 @@ export function palettesModel(models, config) {custom: {}};+ config.vectorStyles = config.vectorStyles || {+ rendered: {}+ };+var self = {};self.events = util.events();self.active = {};- self.getRendered = function (layerId, index) {+ self.getRenderedPalette = function (layerId, index) {var name = config.layers[layerId].palette.id;var palette = config.palettes.rendered[name];if (!lodashIsUndefined(index)) {- palette = palette.maps[index];+ if (palette.maps) {+ palette = palette.maps[index];+ }}return palette;};- self.getCustom = function (paletteId) {+ self.getRenderedVectorStyle = function (layerId, index) {+ var name = config.layers[layerId].vectorStyle.id;+ var vectorStyle = config.vectorStyles.rendered[name];+ if (!lodashIsUndefined(index)) {+ if (vectorStyle.styles) {+ vectorStyle = vectorStyle.styles[index];+ }+ }+ return vectorStyle;+ };++ self.getCustomPalette = function (paletteId) {var palette = config.palettes.custom[paletteId];if (!palette) {throw new Error('Invalid palette: ' + paletteId);@@ -38,13 +55,12 @@ export function palettesModel(models, config) {self.active[layerId] = self.active[layerId] || {};var active = self.active[layerId];active.maps = active.maps || [];- lodashEach(self.getRendered(layerId)- .maps,- function (palette, index) {- if (!active.maps[index]) {- active.maps[index] = lodashCloneDeep(palette);- }- });+ lodashEach(self.getRenderedPalette(layerId).maps,+ function (palette, index) {+ if (!active.maps[index]) {+ active.maps[index] = lodashCloneDeep(palette);+ }+ });};self.allowed = function (layerId) {@@ -111,8 +127,11 @@ export function palettesModel(models, config) {};self.getCount = function (layerId) {- return self.getRendered(layerId)- .maps.length;+ if (self.getRenderedPalette(layerId).maps) {+ return self.getRenderedPalette(layerId).maps.length;+ } else {+ return 0;+ }};/*** Gets a single colormap (entries / legend combo)@@ -130,7 +149,7 @@ export function palettesModel(models, config) {if (self.active[layerId]) {return self.active[layerId].maps[index];}- return self.getRendered(layerId, index);+ return self.getRenderedPalette(layerId, index);};/*** Gets the legend of a colormap@@ -159,7 +178,7 @@ export function palettesModel(models, config) {* @return {object} object of the legend*/self.getDefaultLegend = function (layerId, index) {- var palette = self.getRendered(layerId, index);+ var palette = self.getRenderedPalette(layerId, index);return palette.legend || palette.entries;};@@ -466,7 +485,7 @@ export function palettesModel(models, config) {use = true;return false;}- var rendered = self.getRendered(layerId, index);+ var rendered = self.getRenderedPalette(layerId, index);if (palette.type !== 'classification') {if (palette.min <= 0) {delete palette.min;@@ -505,7 +524,7 @@ export function palettesModel(models, config) {};var source = entries.colors;var target = (palette.custom)- ? self.getCustom(palette.custom)+ ? self.getCustomPalette(palette.custom).colors : source;var min = palette.min || 0;diff --git a/web/js/palettes/palettes.js b/web/js/palettes/palettes.jsindex a29a394bd..f1db89d92 100644--- a/web/js/palettes/palettes.js+++ b/web/js/palettes/palettes.js@@ -102,14 +102,23 @@ export default (function (self) {'custom', 'config/palettes-custom.json');};- self.loadRendered = function (config, layerId) {+ self.loadRenderedPalette = function (config, layerId) {var layer = config.layers[layerId];return util.load.config(config.palettes.rendered,layer.palette.id, 'config/palettes/' + layer.palette.id + '.json');};+ self.loadRenderedVectorStyle = function (config, layerId) {+ var layer = config.layers[layerId];+ return util.load.config(config.vectorStyles.rendered,+ layer.vectorStyle.id, 'config/vectorstyles/' + layer.vectorStyle.id + '.json');+ };+self.requirements = function (state, config) {var promises = [];+ config.vectorStyles = {+ rendered: {}+ };config.palettes = {rendered: {},custom: {}@@ -117,7 +126,9 @@ export default (function (self) {lodashEach(state.l, function (qsLayer) {var layerId = qsLayer.id;if (config.layers[layerId] && config.layers[layerId].palette) {- promises.push(self.loadRendered(config, layerId));+ promises.push(self.loadRenderedPalette(config, layerId));+ } else if (config.layers[layerId] && config.layers[layerId].vectorStyle) {+ promises.push(self.loadRenderedVectorStyle(config, layerId));}var custom = lodashFind(qsLayer.attributes, {id: 'palette'diff --git a/web/js/util/util.js b/web/js/util/util.jsindex f9156d9ce..02e43e631 100644--- a/web/js/util/util.js+++ b/web/js/util/util.js@@ -727,7 +727,21 @@ export default (function (self) {return hex(r) + hex(g) + hex(b) + 'ff';};- self.hexColorDelta = function (hex1, hex2) {+ self.trim = function(str) {+ return str.replace(/^\s+|\s+$/gm, '');+ };++ self.rgbaToShortHex = function(rgba) {+ var parts = rgba.substring(rgba.indexOf('(')).split(',');+ var r = parseInt(self.trim(parts[0].substring(1)), 10);+ var g = parseInt(self.trim(parts[1]), 10);+ var b = parseInt(self.trim(parts[2]), 10);+ var a = parseFloat(self.trim(parts[3].substring(0, parts[3].length - 1))).toFixed(2);++ return ('#' + r.toString(16) + g.toString(16) + b.toString(16) + (a * 255).toString(16).substring(0, 2));+ };++ self.hexColorDelta = function(hex1, hex2) {var r1 = parseInt(hex1.substring(0, 2), 16);var g1 = parseInt(hex1.substring(2, 4), 16);var b1 = parseInt(hex1.substring(4, 6), 16);@@ -738,6 +752,116 @@ export default (function (self) {return Math.sqrt(Math.pow((r1 - r2), 2) + Math.pow((g1 - g2), 2) + Math.pow((b1 - b2), 2));};+ // Changes the RGB/HEX temporarily to a HSL-Value, modifies that value+ // and changes it back to RGB/HEX.+ self.changeHue = function(rgb, degree) {+ var hsl = self.rgbToHSL(rgb);+ hsl.h += degree;+ if (hsl.h > 360) {+ hsl.h -= 360;+ } else if (hsl.h < 0) {+ hsl.h += 360;+ }+ return self.hslToRGB(hsl);+ };++ // exepcts a string and returns an object+ self.rgbToHSL = function(rgb) {+ // strip the leading # if it's there+ rgb = rgb.replace(/^\s*#|\s*$/g, '');++ // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`+ if (rgb.length === 3) {+ rgb = rgb.replace(/(.)/g, '$1$1');+ }++ var r = parseInt(rgb.substr(0, 2), 16) / 255;+ var g = parseInt(rgb.substr(2, 2), 16) / 255;+ var b = parseInt(rgb.substr(4, 2), 16) / 255;+ var cMax = Math.max(r, g, b);+ var cMin = Math.min(r, g, b);+ var delta = cMax - cMin;+ var l = (cMax + cMin) / 2;+ var h = 0;+ var s = 0;++ if (delta === 0) {+ h = 0;+ } else if (cMax === r) {+ h = 60 * (((g - b) / delta) % 6);+ } else if (cMax === g) {+ h = 60 * (((b - r) / delta) + 2);+ } else {+ h = 60 * (((r - g) / delta) + 4);+ }++ if (delta === 0) {+ s = 0;+ } else {+ s = (delta / (1 - Math.abs(2 * l - 1)));+ }++ return {+ h: h,+ s: s,+ l: l+ };+ };++ // expects an object and returns a string+ self.hslToRGB = function(hsl) {+ var h = hsl.h;+ var s = hsl.s;+ var l = hsl.l;+ var c = (1 - Math.abs(2 * l - 1)) * s;+ var x = c * (1 - Math.abs((h / 60) % 2 - 1));+ var m = l - c / 2;+ var r, g, b;++ if (h < 60) {+ r = c;+ g = x;+ b = 0;+ } else if (h < 120) {+ r = x;+ g = c;+ b = 0;+ } else if (h < 180) {+ r = 0;+ g = c;+ b = x;+ } else if (h < 240) {+ r = 0;+ g = x;+ b = c;+ } else if (h < 300) {+ r = x;+ g = 0;+ b = c;+ } else {+ r = c;+ g = 0;+ b = x;+ }++ r = self.normalize_rgb_value(r, m);+ g = self.normalize_rgb_value(g, m);+ b = self.normalize_rgb_value(b, m);++ return self.rgbToHex(r, g, b);+ };++ self.normalize_rgb_value = function(color, m) {+ color = Math.floor((color + m) * 255);+ if (color < 0) {+ color = 0;+ }+ return color;+ };++ self.rgbToHex = function(r, g, b) {+ return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);+ };/*** Submits an AJAX request or retreives the result from the cache.*