将rails变量加载到javascript中

时间:2015-03-11 02:21:32

标签: javascript ruby-on-rails google-maps

我试图使用谷歌地图api和rails从数据库加载标记,但我遇到了麻烦,因为服务器正在加载javascript之前的标记,所以它没有被添加到地图

class SchoolsController < ApplicationController
    def show
        @school = School.friendly.find(params[:id])
        @alerts = Alert.all
    end
    def new
        @school = School.new
        @school.admins.build
    end
    def create
        @school = School.new(school_params)
        @school.save
    end

    private

    def school_params
        params.require(:school).permit(:school_name, :age, admins_attributes: [ :email, :password, :password_confirmation ])
    end
end

显示页面

 <script>

jQuery(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}); 

function initialize() {

        var mapOptions = {
          center: { lat: -34.397, lng: 150.644},
          zoom: 8
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);

        <% @alerts.each do |alert| %>

            var marker = new google.maps.Marker({
              position: "(<%= alert.longitude %>, <%= alert.latitude %>)",
              map: map,
              title:"Hello World!"
        });

        <% end %>

      }
      google.maps.event.addDomListener(window, 'load', initialize);

</script>

0 个答案:

没有答案