Ruby on Rails - Leaflet-rails 'ReferenceError: L is not defined'

Ruby on Rails - Leaflet-rails 'ReferenceError: L is not defined'

我是 Rails 和 Leaflet 上的 Ruby 的新手,但我正在尝试使用 gem 'leaflet-rails' 版本 1.6 和 Rails 版本 6.0.3.2.

here 是关于类似问题的类似线程。

我在加载我的页面时收到 'ReferenceError: L is not defined'。我已经按照安装指南进行操作,并且在过去的 2 晚一直在尝试实施地图,但无济于事。我能够让地图工作的唯一方法是,如果我将下面的代码添加到 HTML 文件中,我试图将地图实现到其中。

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"/> 

我已经检查过并且正在使用传单-rails 1.6.0

我已将“gem 'leaflet-rails'”添加到 Gemfile

我已将“*= require leaflet”添加到 application.css 文件

我已将“//= require”传单添加到 application.js 文件

我已经将下面的代码添加到 application.html.erb

<%= javascript_pack_tag 'application', 'data-turbolinks-track': true %>
<%= stylesheet_link_tag 'application' %>

我已将以下代码添加到我创建的 leaflet.rb 文件中

 ' Leaflet.tile_layer = 'http://{s}.tile.cloudmade.com/YOUR-CLOUDMADE-API-KEY/997/256/{z}/{x}/{y}.png'
# You can also use any other tile layer here if you don't want to use Cloudmade - see http://leafletjs.com/reference.html#tilelayer for more
Leaflet.attribution = 'Your attribution statement'
Leaflet.max_zoom = 18' 

当我刷新页面并检查 HTML 时,脚本是 运行 下面的代码。

var map = L.map('map', {});
map.setView([51.52238797921441, -0.08366235665359283], 18);
L.tileLayer('http://{s}.tile.cloudmade.com/YOUR-CLOUDMADE-API-KEY/997/256/{z}/{x}/{y}.png', {
          attribution: 'Your attribution statement',
          maxZoom: 18,
}).addTo(map);

如果我查看文件的头部,它似乎引用了 application.js 文件,但我看不到它引用了与 Leaflet 相关的任何内容。

<script src="/packs/js/application-9fe6f817df469889a178.js" data-turbolinks-track="true"></script>

由于我对 Rails 还很陌生,所以我不知道接下来要尝试什么。

如有任何帮助,我将不胜感激。问候,罗里。

Blockquote Skip the gem and just install Leaflet through Yarn. You can add the dependency with yarn add leaflet. Front-end packages distributed as gems are an obsolete concept in Rails 6. And where generally problematic as they always lagged behind the package the wrapped. – max

我按照传单-rails github 页面上过时的安装说明进行操作。我通过 gem 安装了传单,现在在 rails 6 中已经过时,所以我所有初始化地图的尝试都没有成功。

The //= require leaflet comment is a Sprockets directive for the old assets pipeline and won't do anything in Webpack. In Webpack you use its require('leaflet') function in your main manifest (or imports). Its a very different beast and you're following outdated instructions. github.com/rails/webpacker – max

然后我通过 yarn 安装了传单,并在 application.js 中使用 require(leaflet) 对其进行了初始化,并将传单 css 添加到它自己的文件中,并在 html.erb 文件中引用了它我正在工作。然后它只是简单地使用内置地图辅助功能并且基本地图正在工作。

 <%= map(:center => {
  :latlng => [51.52238797921441, -0.08366235665359283],
  :zoom => 18
}) %>

感谢 Max 为我解决了这个问题。