9

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

2 Answers 2

13

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);
});
1
  • Thanks, and i will say that this implementation allowed me to use google maps with turbolinks :)
    – dbonadiman
    Commented Jan 13, 2013 at 23:32
0

This doesn't answer your question, but there is a google maps gem that has worked really nicely for me: https://github.com/apneadiving/Google-Maps-for-Rails

1
  • This should be posted as a comment to the Question - as you said yourself, this isn't an answer.
    – deefour
    Commented Jan 14, 2013 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.