Home > Enterprise >  How can I reference a JavaScript variable as a value in an expression with Mapbox?
How can I reference a JavaScript variable as a value in an expression with Mapbox?

Time:02-14

new to mapbox and enjoying my journey so far.

I am curious if there is a way to reference a javascript variable within an expression.

I am trying to essentially reference some color values that are dynamic, However I've had no luck. I went through the MB docs but I havent been able to find information or options that match my conundrum. Thank you for any info, pointers.

const mbFillColorExpressionValue = Object.keys(fills)
   .map(fips => {
      return `"${fips}","${fills[fips].fill}"`;
   })
   .concat('"white"')
   .toString();

(mbFillColorExpressionValue returns a string "18089","#839EBE","18091","#839EBE","18127","#839EBE","white")


  this.map.setPaintProperty('counties-towns', 'fill-color', [
     'match',
     ['get', 'GEOID'],
     geoids,
     mbFillColorExpressionValue
   ]);

CodePudding user response:

After reading the docs of Mapbox, I think the end result should look something like the code below. Each GEOID is paired with its corresponding fill. And the color white as a fallback on the last line.

this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   '18089', '#839EBE',
   '18091', '#839EBE',
   '18127', '#839EBE',
   'white'
]);

To get to that result we first have to change the map method to a flatMap. This is because we can't add any keys when mapping over an array, but we can return an array for each item and the flatten it to turn the whole thing into a single array.

const mbFillColorExpressionValue = Object.keys(fills).flatMap(fips => [fips, fills[fips].fill]);
mbFillColorExpressionValue.push('white');

From here we can use the spread syntax ... to place the contents of the mbFillColorExpressionValue array into the expression.

this.map.setPaintProperty('counties-towns', 'fill-color', [
  'match',
   ['get', 'GEOID'],
   ...mbFillColorExpressionValue
]);
  • Related