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?
Short answer with pad to exact size
'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)
Use
getRandomColor()
in place of"#0000FF"
:http://jsfiddle.net/XmqDz/1/
A breakdown of how this works:
Math.random()*256
gets a random (floating point) number from 0 to 256 (0 to 255 inclusive)Example result: 116.15200161933899
Adding the
|0
strips off everything after the decimal point.Ex: 116.15200161933899 -> 116
Using
.toString(16)
converts this number to hexadecimal (base 16).Ex: 116 -> 74
Another ex: 228 -> e4
Adding
"0"
pads it with a zero. This will be important when we get the substring, since our final result must have two characters for each color.Ex: 74 -> 074
Another ex: 8 -> 08
.substr(-2)
gets just the last two characters.Ex: 074 -> 74
Another ex: 08 -> 08 (if we hadn't added the
"0"
, this would have produced "8" instead of "08")The
for
loop runs this loop three times, adding each result to the color string, producing something like this:#7408e4
My version: