2

I'm using Leaflet.js the leaflet-js' gem, but can't figure out the syntax to get the map to show.

<div id="map">
  <%=
  var map = L.map('map').setView([-41.2858, 174.78682], 14);
  mapLink = 
      '<a href="http://openstreetmap.org">OpenStreetMap</a>';
  L.tileLayer(
      'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; ' + mapLink,
      maxZoom: 18,
      }).addTo(map);
  %>
</div>

produces the error uninitialized constant ActionView::CompiledTemplates::L. What is the correct formatting and is there a guide on how to translate regular javascript for use with Rails? Thank you for any help.

2 Answers 2

2

Looks like you're using <%= which is for embedded Ruby to use JavaScript.

The Ruby interpreter is thus trying to read your code as if it was Ruby, hence the error.

Try something like:

<div id="map"></div>
<script language="JavaScript">
  var map = L.map('map').setView([-41.2858, 174.78682], 14);
  mapLink = 
      '<a href="http://openstreetmap.org">OpenStreetMap</a>';
  L.tileLayer(
      'http://<%= s %>.tile.openstreetmap.org/<%= z %>/<%= x %>/<%= y %>.png', {
      attribution: 'Map data &copy; ' + mapLink,
      maxZoom: 18,
      }).addTo(map);
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

I think having it interpreted is the point. Here's code for another gem github.com/axyjo/leaflet-rails and I'm looking for similar for leaflet-js. <%= map(:center => { :latlng => [51.52238797921441, -0.08366235665359283], :zoom => 18 }) %>
Leaflet-js contains basically the assets for Leaflet, whereas Leaflet-rails has view helpers. If you continue using leaflet-js, you may have to write a view helper.
Reuben: Thanks, I didn't get that was the difference. So I need a view helper to run in in Rails. In my newbie state, I assumed since it was a gem it was meant to work in Rails.
0

I'm not adding much, except to say now I get the difference between the two gems. The Leaflet-rails helper gem gets the syntax slightly wrong and therefore doesn't work. This (almost) works

<div id="map">
  <script>
    var map = L.map('map').setView([<%= @location.latitude %>, <%= @location.longitude %>], 16);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
              attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
              maxZoom: 19,
    }).addTo(map);
        marker = L.marker([<%= @location.latitude %>, <%= @location.longitude %>]).addTo(map)
  </script>
</div>

I still need to work on the marker. Only shows a question mark.

Thanks for the help

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.