Rails - javascript configuration definition

I worked 4 years to figure out how I can use Google maps in my Rails application.

I tried using gmaps4rails, but refused because it is too complicated. I managed to find a solution on SO that worked, except that I could not specify the level of scaling. However, in production all my other javascripts did not work. The solution for this was to move:

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

from the title tag to the bottom of the body tag.

This works so that all my other js files work the same as in the development environment, but in production mode now the map will not be displayed at all.

Is there a solution that:

  • allows me to use javascript files (except google maps javascript file), which I think is achieved thanks to the presence of javascript include tag at the end of the body instead of the head

  • allows me to display google map? If I move the javascript include tag to my head, I can display the map, but the rest of my js files do not work (production only).

  • Allows you to specify the zoom level on my map?

I tried to ask for help here , here and here (and another million times on this board). I have not yet been able to find help.

In my address.js, I have:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5
  });
  var bounds = new google.maps.LatLngBounds();
  // var opts = {
  //   zoom: 10,
  //   max_zoom: 16
  // }

  var n = addresses.length;
  for (var i = 0; i < n; i++) {
    var lat = addresses[i].latitude;
    var lng = addresses[i].longitude;
    if (lat == null || lng ==null){
      console.log(addresses[i].name + " doesn't have coordinates");
    }else {
      var address = new google.maps.Marker({
        position: {lat: parseFloat(lat), lng: parseFloat(lng)},
        title: addresses[i].name,
        map: map //,
//        zoom: 8
      });
      bounds.extend(address.position);
    }
  }
  map.fitBounds(bounds);
}

As I stated in the message, I get an error message:

initMap is not a function

, , .

js, , - , , . , 2 , - , , , , - , - SO ( , ) "setZoom" "zoom: 5". , .

, js ( google) , javascript include . . , , , . , . , , , , - , js . js,

config.rb

config/initializers/assets.rb

# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
config/production.rb

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

, ( , . , , ( ). , . , ( 100 , ) , .

, . , , - .

R_G

address.js, . :

;(function ready() {
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5
  });
  var bounds = new google.maps.LatLngBounds();
  // var opts = {
  //   zoom: 10,
  //   max_zoom: 16
  // }

  var n = addresses.length;
  for (var i = 0; i < n; i++) {
    var lat = addresses[i].latitude;
    var lng = addresses[i].longitude;
    if (lat == null || lng ==null){
      console.log(addresses[i].name + " doesn't have coordinates");
    }else {
      var address = new google.maps.Marker({
        position: {lat: parseFloat(lat), lng: parseFloat(lng)},
        title: addresses[i].name,
        map: map //,
//        zoom: 8
      });
      bounds.extend(address.position);
    }
  }
  map.fitBounds(bounds);
}
})();

, - ( , ). ( , , , R_G).

DAVE :

Q1: ?

- , production.rb . . :

# Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

, , assets.rb , . , , , , -.

asset.rb :

# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.# Do not fallback to assets pipeline if a precompiled asset is missed.

, , application.js , . ( , , ).

address.js application.js( require), , asset.rb.

Q2. application.js

. .

: ", JS application.js, , assets.rb, address.js, , ".

.js :

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-fileupload/vendor/jquery.ui.widget
//= require jquery-fileupload/jquery.iframe-transport
//= require jquery-fileupload/jquery.fileupload
//= require bootstrap-sprockets
//= require moment
//= require bootstrap-datetimepicker
//= require pickers
// require underscore
// require gmaps/google
//= require markerclusterer
//= require cocoon
//= require cable
//= require_tree .

. Address.js app/assets/javascripts, require_tree application.js

, . , ? assets.rb production.rb?

" " ""? , , .

ENGINEERDAVE COMMENT ON R_G SUGGESTION

EngineerDave . :

  • javascript include body ( , , google , hide/show js , ).

  • :

    document.addEventListener( "DOMContentLoaded", () { // });

, :

javascript , - , : stackoverflow.com/questions/9899372/... - jfriend00 13 7:58

:

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here

})();
</script>

address.js :

function initMap() {

, :

(function() {
  function initMap() {
   //then continue with the rest of my address.js file
})();

, , R_G. . , .

DOWNVOTE

. javascript. codementor.io/upwork , , . , . , . 4+ , . . , . . , codementor.io. , , , . , , , - . .

, , .

BRENZY

, , . , - . , . , , . , , :

Application.html.erb

:

  • javascript include

  • js include google. , , , . , , - API, .

    <%= csrf_meta_tags %>
    <%= favicon_link_tag %>
    <!-- <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> -->
    <script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV["GOOGLE_MAPS_API_KEY"] %>"async defer></script>
    
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <!-- Latest compiled and minified CSS -->
    <%= stylesheet_link_tag  href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" %>
    
    <!-- Optional theme -->
    <%= stylesheet_link_tag href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css" %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    

//JavaScripts/initialise.js

- .

function initialize() {
  var losAngeles = new google.maps.LatLng(34.0500, -118.2500);
  var pasadena = new google.maps.LatLng(34.14778, -118.14452);
  var mapOptions = {
    zoom: 10,
    center: losAngeles,
    disableDefaultUI: true,
    mapTypeControlOptions: google.maps.MapTypeId.SATELLITE
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

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

.

, , , , . , application.js require_tree, , , , app/assets/javascripts .

, :

<div id="map-canvas"></div>

, :

Uncaught ReferenceError: google is not defined
    at initialize.self-f919dc6….js?body=1:13
(anonymous) @ initialize.self-f919dc6….js?body=1:13

.

. js, , . , javascript include .

js app/assets/javascripts/stance/commercial.js

jQuery(document).ready(function() {
   jQuery('[name="organisation[commercial_attributes][standard_financial_split]"]').on('click', function() {
      if (jQuery(this).val() == 'true' ) {
          jQuery('#commercial_standard_financial_split_content').removeClass('hidden');
      } else {
          jQuery('#commercial_standard_financial_split_content').removeClass('hidden').addClass('hidden');
      }
   });

});

, javascript include body. , - .

+4
2

: . , , . , , , . , , . ( ) JavaScript, , , . "() {...}", . , script. , , , , "initMap ". , .


, , , ...

, , . , .

JavaScript :

;(function() {
    // Document is ready here
})();

jQuery, :

;$(function ($, window, document) {
    // Document ready here
}(window.jQuery, window, document));

, , , , .

, .


: , , . :

;(function() {
    // Document is ready here
})();

"// " . , , .

, , . . ​​ . , , - . , . .

+2

Rails 5 https://github.com/brenzy/sample1, google dev, .

1) google script , application.js:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

2) EngineerDave , , .

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

.

, , , , .

+1

Source: https://habr.com/ru/post/1663433/


All Articles