私の答えはかなり長いですが、うまくいくようです。私が見つけたブログ投稿からいくつかのコードを取得しました。これは、異なる可能性があり、読みやすい色を生成する可能性があります。
ルート名の最初の文字に基づいて、市場ごとに異なる文字を割り当てます。次に、ルートごとに一意で一貫性のある色が割り当てられます。つまり、2つのルートの最初の文字が同じであっても、色が異なる可能性が高くなります。
やるべきリファクタリングがたくさんあることは間違いありません!
def index
@premise = @company.premises.find(params[:premise]) if params[:premise]
#only generate the map info if a premise has been selected
if @premise.present?
@json = @company.addresses.approved.where(:route_id => @premise.routes).to_gmaps4rails do |address, marker|
marker.picture({
:picture => "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=#{address.route.name[0]}|#{random_colour_by_index(address.route.name)}|000000"
})
marker.title "#{address.route.name}"
end
end
end
private
def random_colour_by_index(index)
@colour ||= Hash.new
@colour[index] ||= array_rgb_to_hex(hsv_to_rgb(rand, 0.5, 0.95))
end
def array_rgb_to_hex(rgb)
rgb.inject("") { |hex, element| hex + single_rgb_to_hex(element) }
end
def single_rgb_to_hex(rgb)
hex = rgb.to_s(16)
rgb < 16 ? "0#{hex}" : hex
end
def hsv_to_rgb(h, s, v)
h_i = (h*6).to_i
f = h*6 - h_i
p = v * (1 - s)
q = v * (1 - f*s)
t = v * (1 - (1 - f) * s)
r, g, b = v, t, p if h_i==0
r, g, b = q, v, p if h_i==1
r, g, b = p, v, t if h_i==2
r, g, b = p, q, v if h_i==3
r, g, b = t, p, v if h_i==4
r, g, b = v, p, q if h_i==5
[(r*256).to_i, (g*256).to_i, (b*256).to_i]
end