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');

  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(
    maxZoom: 18,
      '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>',

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