我的回答相当冗长,但似乎工作正常。我从我发现的一篇博客文章中获取了一些代码,这些代码可以生成可能既不同又可读的颜色。
我根据路线名称的第一个字母为每个市场分配一个不同的字母。然后分配一种颜色,该颜色对于每条路线都是唯一且一致的。这意味着即使两条路线的首字母相同,它们也很有可能具有不同的颜色。
毫无疑问,有很多重构要做!
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