The us-map plugin was already in use elsewhere and I wanted to create a clickable map that would display an anchor state and allow for configuration of related states.
Also in use is the gon gem to allow passing of data directly into Javascript, included in a Rails 4.1 project.
Controller code:
# assume @state is the current state
gon.current_state_code = @state.state_code
gon.regional_states = @state.related_state_codes # returns ["AL", "AK", ...]
View code:
<%# this is inside a form and states_list maintains the current list of selected states%>
<%= hidden_field_tag 'states_list' %>
Associated CoffeeScript:
states = ->
# initialize the hidden field for states selected
$('#states_list').val(JSON.stringify(gon.regional_states))
$('#map').usmap(
stateStyles:
fill: 'lightGray'
stateSpecificStyles: do ->
# current state is red, selected states green
specificStyles = {}
specificStyles[gon.current_state_code] = fill: 'red'
for state in gon.regional_states
specificStyles[state] = fill: 'green'
specificStyles
click: (event, data) ->
# don't allow current state to be selected
if data.name != gon.current_state_code
# add green as a specific style or delete to toggle state highlight
if this.stateSpecificStyles[data.name]
delete this.stateSpecificStyles[data.name]
else
this.stateSpecificStyles[data.name] = fill: 'green'
# this could be more intelligent, but I'm just recalculating along the way
regionalStates = []
for key of this.stateSpecificStyles
if this.stateSpecificStyles[key]['fill'] != 'red'
regionalStates.push(key)
$('#states_list').val(JSON.stringify(regionalStates))
)
$(document).ready ->
if gon? && gon.regional_states?
states()