Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's possible to put Google Map's Javascripts in the Asset pipeline (Rails)?

I added the javascript needed to load the google maps into 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 parameters latitude and longitude when i load the map. As i said in the title i want to put these javascripts into the asset pipeline, is it possible if yes how ? thanks

like image 645
dbonadiman Avatar asked Jan 13 '13 22:01

dbonadiman


1 Answers

You should not include the Google Maps API in your asset-pipeline-generated application.js file. Instead it should be included as a separate <script> tag before your application.js's <script> tag.

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

You'll probably want to make @lat and @lon arguments of your initialize method though so they can be defined within your pages <head>. For example, you might 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);
});
like image 178
deefour Avatar answered Nov 15 '22 17:11

deefour