Javascript js.coffee.erb-同步问题?
我正在尝试将数据库中的纬度和经度值插入到我的谷歌地图咖啡脚本中Javascript js.coffee.erb-同步问题?,javascript,ruby-on-rails-3,google-maps-api-3,coffeescript,erb,Javascript,Ruby On Rails 3,Google Maps Api 3,Coffeescript,Erb,我正在尝试将数据库中的纬度和经度值插入到我的谷歌地图咖啡脚本中 jQuery -> initialize() initialize = -> myOptions = center: new google.maps.LatLng(<%= @location.latitude %>, <%= @location.longitude %>) zoom: 12 mapTypeControlOptions: {mapTypeIds: [
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
建议我的定位对象
@location = Location.find(params[:id])
在解析js.coffee.erb文件时尚未实例化。(??)
我已经用硬编码值测试了coffeescript,@location.latitude在我看来工作得非常好。
知道哪里出了问题吗?在控制器运行之前,您的(Java | Coffee)脚本资产将被处理并发送到浏览器。这意味着@location
不会来自您的控制器,它将来自您的.js.coffee.erb
转换为JavaScript时发生的任何self
。在部署到生产环境时,这些资产将(或至少应该)在任何东西进入您的生产系统之前进行编译,因此@location
没有任何有用的希望
您应该在控制器的ERB而不是资产中构建数据:
<!-- Somewhere in the appropriate app/views/... file... -->
<script type="text/javascript">
window.global_location = { lat: <%= @location.latitude %>, lng: <%= @location.longitude %> };
</script>
或者您可以尝试通过AJAX调用加载位置
对于每个应用程序常量和配置值,只在资产中使用ERB,不要尝试在资产中使用ERB来处理在应用程序运行时会发生更改的任何内容。是的,我曾想过类似的事情。感谢您提供的信息,我想长期AJAX是更优雅的解决方案。我会将
数据坐标=“{lat:,lng:”
放在#map#u canvas上,然后用$('#map#u canvas')。数据('坐标')
@Guillaume86:这也是一个很好的方法,或者根据情况将数据lat
和数据lng
属性分开。
<!-- Somewhere in the appropriate app/views/... file... -->
<script type="text/javascript">
window.global_location = { lat: <%= @location.latitude %>, lng: <%= @location.longitude %> };
</script>
center: new google.maps.LatLng(global_loc.lat, global_loc.lng)