0
votes

I'm making an interactive map with Leaflet. I've markers on the map (based on their longitude and latitude coordinates) and I want some markers to have a different color than others. For example, some coordinates I give it a score of "10" and I want it to be pink while the other markers have a score of "5" and I want to give the markers they have red.

I have a marker.js file:

var myIcon = L.icon({
  iconUrl: 'icon_ping.png',
  iconSize: [20, 15],
  iconAnchor: [5, 23],
  popupAnchor: [0, -11]
});


for ( var i=0; i < markers.length; ++i ) 
{
 L.marker( [markers[i].lat, markers[i].lng], {icon: myIcon} )
  .bindPopup( '<a target="_blank">' + markers[i].name + '<br>' + markers[i].address + '<br>' +'Score: ' + markers[i].score + '</a>' )
  .addTo( map );
}

I also have a coordinates.json file that contains the coordinates and my scores

markers = [
    {
     "name": "Place",
     "address": "123, TX",
     "score": "10",
     "lat": 12.123,
     "lng": 23.234
    }

    ...

];

Basically I just want the markers of the same scores to have the same color marker. I was thinking that I need to create another var myIcon_2 and put a if statement inside the for loop? Will that work or is there another better way to approach this?

Thanks.

1
Yes the way you've described would be the way to do it :) - rwacarter

1 Answers

2
votes

The way you've described it would be the way to do it.. However to avoid duplicating a lot of code etc, you should use a ternary operator to define the icon, ie:

var myIcon = L.icon({
    iconUrl: 'icon_ping.png',
    iconSize: [20, 15],
    iconAnchor: [5, 23],
    popupAnchor: [0, -11]
  }),
  myIcon2 = L.icon({
    iconUrl: 'icon_ping2.png',
    iconSize: [20, 15],
    iconAnchor: [5, 23],
    popupAnchor: [0, -11]
  });


for ( var i=0; i < markers.length; ++i ) 
{
    var icon = markers[i].score === 10 ? myIcon2 : myIcon;

     L.marker( [markers[i].lat, markers[i].lng], {icon: icon} )
       .bindPopup( '<a target="_blank">' + markers[i].name + '<br>' + markers[i].address + '<br>' +'Score: ' + markers[i].score + '</a>' )
       .addTo( map );
}