Can I put Google Map Javascripts in an Asset (Rails) pipeline?

I added the javascript needed to upload Google maps to my page:

<% content_for :head do %> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"> </script> <script type="text/javascript"> function initialize() { var mapOptions = { center: new google.maps.LatLng(<%=@lat%>, <%=@lon%>), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } </script> <% end %> 

as you can see, I need to pass the latitude and longitude parameters when I load the map. As I said in the title, I want to place these javascripts in the asset pipeline, is it possible, if so, how? thanks

+8
javascript ruby-on-rails asset-pipeline
source share
2 answers

You should not include the Google Maps API in the application.js file created using the pipeline. Instead, it should be included as a separate <script> tag before your application.js <script> .

You can then add your initialize() method to any file included in the pipeline of your asset, including application.js .

You will probably want to make the @lat and @lon your initialize method, although they can be defined on your <head> pages. For example, you may have

 <head> <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"></script> <%= javascript_include_tag "application" %> <script> var latitude = <%= @lat %>; var longitude = <%= @lon %>; </script> </head> 

and in your application.js file you might have

 function initialize(latitude, longitude) { var mapOptions = { center: new google.maps.LatLng(latitude, longitude), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } $(function() { initialize(latitude, longitude); }); 
+12
source share

This does not answer your question, but there is a google gem that works fine for me: https://github.com/apneadiving/Google-Maps-for-Rails

0
source share

All Articles