Given this function, I want to replace the color with a random color generator.
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
How can I do it?
Array.prototype.reduce
makes it very clean.Needs a shim for old browsers.
This function goes above and beyond other answers in two ways:
It attempts to generate colors as distinct as possible by finding which color out of 20 tries has the farthest euclidian distance from the others in the HSV cone
It allows you to restrict the hue, saturation, or value range, but still attempts to pick colors as distinct as possible within that range.
It's not super efficient, but for reasonable values (who could even pick apart 100 colors easily?) It's fast enough.
See JSFiddle
Here's a twist on the solution provided by @Anatoliy.
I needed to generate only light colours (for backgrounds), so I went with three letter (#AAA) format:
The top voted comment of the top answer suggests that Martin Ankerl's approach is better than random hex numbers, and although I haven't improved on Ankerl's methodology, I have successfully translated it to JavaScript. I figured I'd post an additional answer to this already mega-sized SO thread because the top answer has another comment linking to a Gist with the JS implementation of Ankerl's logic and that link is broken (404). If I had the reputation, I would have simply commented the jsbin link I created.
https://jsbin.com/qeyevoj/edit?js,console
This can be very easily be found using Google Search:
Updated version:
Use distinct-colors.
It generates a palette of visually distinct colors.
distinct-colors is highly configurable: