-2

Is it possible to add if statement into my code inline where the var marker is being set ?

The code;

for (var i = 0; i < addressPoints.length; i++) {
  var a = addressPoints[i];
  var title = a[1];
  var customPopup_3 = " ";

  var marker = L.marker(new L.LatLng(a[9], a[8]), {
    title: title,
    icon: a[11]
  });

  marker.bindPopup(customPopup_3, customOptions);
    markers.addLayer(marker);
  }

  map.addLayer(markers);
}

The things I need to do is add if statement in

var marker = L.marker(new L.LatLng(a[9], a[8]), {
  title: title,
  icon: a[11]
});

This section , so it will look like this:

var marker = L.marker(new L.LatLng(a[9], a[8]), {
  title: title,

  if (a[6] == 3) {
    icon: a[11]
  } else {
    icon: a[12]
  }
});
chrisg86
  • 11,548
  • 2
  • 16
  • 30
Maaverick
  • 63
  • 1
  • 8
  • 1
    You are probably looking for ternary condition, this is how it works: `var x = condition ? option1 : option 2` – Prathamesh Koshti Dec 04 '20 at 12:18
  • 1
    Does this answer your question? [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – ASDFGerte Dec 04 '20 at 12:24

3 Answers3

3

Sure, are you looking for ternary operator like this?:

var marker = L.marker(new L.LatLng(a[9], a[8]), {
   title: title,
   icon: a[6] === 3 ? a[11] : a[12],
});

You can always call a function to do more logic if needed.

const resolveIcon = (a) => {
    if (a[6] === 3) {
        return a[11];
    }
    return a[12];
}

var marker = L.marker(new L.LatLng(a[9], a[8]), {
   title: title,
   icon: resolveIcon(a),
});
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • Thank you for your answer. But what if I need to compare multiple units ? For example a[6] === 1 and a[a6] === 3 etc.. ? – Maaverick Dec 04 '20 at 12:20
  • 1
    @Maaverick I added an example to show how to call a function so the logic can be whatever you'd like. – Davin Tryon Dec 04 '20 at 12:21
1

I think you should be able to use inline if statement like this:

ar marker = L.marker(new L.LatLng(a[9], a[8]), {
title: title,
icon: a[6] === 3 ? a[11] : a[12],
});

Basically, what I'm using is the ? symbol to make an if statement. If the statement before ? is true, then it will return the value before :. If it is false, it will return the value after :.

BrianZhang
  • 153
  • 1
  • 8
0

Save the second argument for L.marker in a separate variable and do your logic upfront:

const options = {
  title: title,
  icon: a[12]
};

if (a[6] === 3) {
  options.icon = a[11]
}

var marker = L.marker(new L.LatLng(a[9], a[8]), options);
chrisg86
  • 11,548
  • 2
  • 16
  • 30