[GIS] Coloring circleMarkers based on category in Leaflet

dynamicjavascriptleaflet

My question is, how can I get Leaflet to color each of circleMarkers I am generating/points with a different color, based off the type property of the point?

I've done a bit of research, but all I've seen is coloring points based on manually created dictionary, while my "known list of types" can be expanded at any time, and additional colors have to be added to accommodate new types of points. Also I am quite weak in Javascript and its actual syntax.

I have the list of all unique types before the iteration over data.

I am working in C# MVC if that helps.

My view (presentation layer of the program – generates a HTML page based off its contents) iterates over Model data (basically data which I need to show on the map) which contains latitude, longitude and type properties (more than that, but irrelevant for this), and adds the points to map, drawing them.

Code that generates my points:

{
foreach (var item in Model)
{
    <text>var point = L.circleMarker(["@item.Latitude",     "@item.Longitude"]).addTo(mymap)
        .bindPopup("@item.Type.TypeDesc" + ", " + "@item.Latitude" + ", " +     "@item.Longitude" + ", " + "@item.RPT_DT").openPopup(); </text>
}
}

I need each point to be of a color depending on TypeDesc property. List of TypeDesc properties can be easily accessed via a Viewbag.TypeDesc list.

Best Answer

Elaborating on the third option in OP's answer:

Code

I'm assuming that you have an array of points with coordinates and categories. This differs slightly from the OP's question. Using the ES6 standard of JavaScript and palette.js from Google, you can automatically colour your points like this:

//Get an array of unique categories
//Reference: [1]
var uniqueCategories = [...new Set(points.map(function(point) {
    return point.category
}))]

//Create palette ('mpn65' has up to 65 different colours)
var palette = palette('mpn65',uniqueCategories.length);

//Construct empty JavaScript Map (keys mapped to values)
//Reference: [2]
var paletteMap = new Map()

//Map all categories to a RGB colour string
for(let i = 0; i < palette.length; i++) {
    paletteMap.set(uniqueCategories[i],palette[i])
}

//Add circleMarkers to Leaflet map
for (let point of points) {
  L.circleMarker(point.coordinates,
                 {color: '#' + paletteMap.get(point.category)} //retrieve mapped colour
                ).addTo(map)
}

Links

[1] https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates#14438954
[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Working example

There is a working example hosted on Codepen: https://codepen.io/anon/pen/zmNLdZ?editors=0010#0