简体   繁体   中英

OpenLayers 3 change point fill color depending on feature parameter value?

I'm populating my map with geojson and all my points have a feature parameter with a specific numeric value. It's a map with temperature values.

Each of this points will need a different fill color depending on the value.

I'm looking for ways to improve my code here. The return value will create the fill color of each point:

 var tempVal = feature.get('tempertaure_value');
 var tempNum = Number(tempVal.toFixed());

switch (true) {
    case tempNum == -30:
        return '#0e0e15';
        break;
    case tempNum == -29:
        return '#0d131f';
        break;
    case tempNum == -28:
        return '#0e1226';
        break;
     ... etc ...
    }

Can I create a multidimensional array that loops for a key value and returns the color value?

I would appreciate help for a better solution that what I currently have because my switch statement has become massive, up to 81 temperature values (from -30 to 50 degrees).

I would create an object like:

var colors = {
  '-30': '#0e0e15',
  '-29': '...',
  '-28': '...'
};

To access:

// just supposing here
var tempVal = feature.get('tempertaure_value');
var color = colors[tempVal];

You could use Chroma.js . You pass the needed colors into the range method and their respective values to the domain method:

var scale = chroma.scale(['blue', 'yellow', 'red']).domain([-30, 10 , 50]);

It returns a method you can use to return a color based on the value you pass as the parameter:

scale(-30).hex(); // returns hex code for blue
scale(10).hex();  // returns hex code for yellow
scale(30).hex();  // returns hex code for orange
scale(50).hex();  // returns hex code for red

Here's an example on Plunker: http://plnkr.co/edit/k5HPfi?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM