xkozn blog

Software Engineer // Runner // Always on the move

Setting up LeafletJS on Rails 6

Posted at — Sep 28, 2019

Add leaflet package

./bin/yarn add leaflet

Edit webpack env to include javascript in build

# config/webpack/environment.js

const { environment } = require('@rails/webpacker');
const webpack = require('webpack');

environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    L: 'leaflet',
  }),
);

module.exports = environment;

Add Leaflet CSS to the webpage. This can be done with css, scss, sass, etc through webpack.

An easy way for now is to add to the application layout page.

<%= stylesheet_link_tag 'https://unpkg.com/leaflet@1.5.1/dist/leaflet.css' %>

Add javascript to create map

const app = this;
if (app.map) app.map.remove();

app.map = L.map('location-map').setView([app.lat, app.long], 14);
const tileLayer = L.tileLayer(
  'https://cartodb-basemaps-{s}.global.ssl.fastly.net/rastertiles/voyager/{z}/{x}/{y}.png',
  {
    maxZoom: 18,
    attribution:
      '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>',
  },
);
tileLayer.addTo(app.map);

const marker = L.marker([app.lat, app.long]).addTo(app.map);
marker.bindPopup('<b>' + app.address + '</b');