LiveView with Mapboxgl JS

I have gotten more and more comfortable with LiveView but am now exploring starting to interop more with javascript libraries such as mapbox-gl (https://docs.mapbox.com/mapbox-gl-js/example/simple-map/).

I am trying to initialize a map (not doing anything else yet but will eventually add markers, etc). I feel like I am missing something basic here so any help would go a long way towards my understanding!

map_live.ex code

defmodule AppWeb.MapLive do
  use AppWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    {:ok, socket}
  end

end

map_live.html.leex code

 <div id="map" phx-hook="MainMap"></div>

app.js relevant code

import mapboxgl from 'mapbox-gl';

let Hooks = {}
Hooks.MainMap = {
  initMap() {
    mapboxgl.accessToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

    const map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/outdoors-v11',
      center: [-122.4376, 37.7577],
      zoom: 8
    });
  },

  mounted() {
    this.initMap();
  }
}

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, hooks: Hooks })

:wave:

What doesn’t work in your case?

The page loads with a div but it is blank, no map. I tried to put console log statements in the javascript but they dont trigger either so I was thinking I was misunderstanding the syntax somewhere.

Did you try using pix-ignore on the map div?

I tried phx-update=“ignore” on the map div and it didnt change the result. Still just an empty div on the page.

The name of the callback in the hook is mounted, not mount.

3 Likes

Thank you! Your are right, that fixed it!