Search code examples
reactjsleaflet

Leaftlet Circlemarker Color


Hi I was wondering how I would go about changing react leaflet circle marker colors based on unique IDs.

right now my circle markers look like this:

         <CircleMarker
            key={index}
            center={[value?.Latitude, value?.Longitude]}
            radius={15}
            color="pink"
          >

and I have an ID value being passed with my Lats and Longs.

value: {
                Latitude: number
                Longitude: number
                ID: string
              },

Don't know if it's helpful, but In R there was a pal feature where I could do something like

pal <- colorFactor(rainbow(4), domain = unique(tmp$ID), levels = unique(tmp$ID))

and then pass it as an option

clusterOptions=markerClusterOptions(), color = pal(tmp$ID))

I'm not sure how to do this in React.

Thank you in advance!

EDIT:

Data is based on a query but this is basically it's format:

const data = [
    {
      Latitude: 0,
      Longitude: 0,
      ID: '206520',
    },
    {
        Latitude: 10,
        Longitude: 10,
        ID: '206520',
    },    
    {
        Latitude: 1,
        Longitude: 1,
        ID: '200000',
      },    {
        Latitude: 1,
        Longitude: 1,
        ID: '300400500',
      },
    ]

If the ID is the same, they should return the same color. So for example mappings with 206520 should both be the same color.


Solution

  • I ended up solving it with the help of kbouls comments and answer.

    First you create an array of unique/ distinct numbers based on the ID field. For me it's a distinct query, but it could just be a function where you push all elements to a list and remove duplicates. Either way let's call it UniqueList.

    Next you create a list of the colors you would like.

    //can be the word 'red' or the code '#ef4444'
        const colors = [
          '#ef4444',
          '#d97706',
          '#0284c7',
          '#d946ef',
        ]
    

    Now that there are two lists, you can tie them together

      const ColorMatched = {}
    
      uniqueList.forEach((element, index) => {
        ColorMatched[element] = colors[index]
      })
    

    You should an output like {206520 : '#ef4444' } //ect

    Now kbouls code can be implemented with

    const getColor = (ID) => {
      return colorIds[ID];
    };
    

    and

      <CircleMarker
        key={index}
        center={[value?.Latitude, value?.Longitude]}
        radius={15}
        color={getColor(value.ID)}
      />
    

    As value.ID calls back the corresponding color. E.g Color = {'#ef4444'}