I am trying to insert latitude and longitude values from a database into my google maps coffeescript.
jQuery ->
initialize()
initialize = ->
myOptions =
center: new google.maps.LatLng(<%= @location.latitude %>, <%= @location.longitude %>)
zoom: 12
mapTypeControlOptions: {mapTypeIds: ["OSM", "OCM", "MQ", google.maps.MapTypeId.HYBRID]}
map = new google.maps.Map $('#map_canvas')[0], myOptions
[…]
I get the following error message:
undefined method `latitude' for nil:NilClass
(in /Users/sg/rails-projects/geo_rails_test/app/assets/javascripts/gmap.js.coffee.erb)
suggesting that my Location Object
@location = Location.find(params[:id])
has not yet been instantiated at the time of parsing the js.coffee.erb file. (??)
I have tested the coffeescript with hard-coded values and @location.latitude works perfectly in my view.
Any ideas what’s going wrong?
Your (Java|Coffee)Script assets will be processed and sent to the browser before your controller even runs. That means that
@locationwon’t come from your controller, it will come from whateverselfhappens to be when your.js.coffee.erbis converted to JavaScript. When deploying to production, the assets will (or at least should be) compiled before anything even hits your production system so@locationhas no hope of being anything useful.You should build your data in your controller’s ERB rather than the asset:
and then your asset can get the data through the
this_locationglobal:Or you could try loading the location through an AJAX call.
Only use ERB in your assets for per-application constants and configuration values, don’t try to use ERB in your assets for anything that will change while your application is running.