csnake
csnake

Reputation: 111

Leaflet circle color depend on variable

I want the color of the circle in Leaflet to depend on a variable. Current code looks like this and does not work:

              function displayMapLatLng
             (lat, lng, boolean,  displayInfo) {
              var latlng =
              new L.LatLng(lat, lng);

              var color =
                  if (boolean =='Y'){
                                      "blue"
                                      }else{
                                      "red"
                                      }

              var circle =
                  new L.circle ((latlng), 20, {color: 'color', opacity:.5})
                  circle.addTo(map);

Anyone know how to solve this?

Upvotes: 1

Views: 7758

Answers (2)

pstenstrm
pstenstrm

Reputation: 6489

Your if statement is not valid JavaScript. You can write it as a trenary operation instead:

function displayMapLatLng (lat, lng, boolean,  displayInfo) {
    var latlng = new L.LatLng(lat, lng);
    var color = (boolean === 'Y') ? "blue" : "red";

    var circle = new L.circle ((latlng), 20, {color: color, opacity:.5})
    circle.addTo(map);
}

boolean is a strange name for a string variable too. If it actually is a boolean value you can write the operation as:

var color = (boolean) ? "blue" : "red";

Update:

In the case where you have more possible color values a trenary operation would be less useful. Then an if ... else if statement or switch statement would be more appropriate:

var color;

switch(boolean) {
    case 'B':
        color = 'blue';
        break;
    case 'R':
        color = 'red';
        break;
    case 'W':
        color = 'white';
        break;
    case 'K': // as in kobolt
        color = 'black';
        break;
    default: 
        color = 'yellow';
        break;
}

The default case will be used when no other case matches boolean.

Upvotes: 4

Armand
Armand

Reputation: 24343

I suspect your code to choose the colour has a syntax error.

If typeof boolean === 'string', try:

var color = boolean == 'Y' ? 'blue' : 'red';

But if, more logically, typeof boolean === 'boolean', try:

var color = boolean ? 'blue' : 'red';

Upvotes: 0

Related Questions