Initializing MapboxGL.js within a single page app

Use a custom element

customElements.define('mapbox-gl', class extends HTMLElement {
  constructor() {
    super()
    this._zoom = 0
  }
  get zoom() {
    return this._zoom
  }
  set zoom(value) {
    if (this._zoom === value) return
    this._zoom = value
    if (!this._map) return
    this._map.setZoom(this._zoom)
  }
  connectedCallback() {
    this._map = new Map({
      container: this,
      zoom: this._zoom
    })
  }
  disconnectedCallback() {
    this._map.remove()
  }
})

zoom : Int -> Html.Attribute msg
zoom howMuch =
    Html.Attributes.property "zoom" (Json.Encode.int howMuch)


mapbox : List (Html.Attribute msg) -> Html msg
mapbox attrs =
    Html.node "mapbox-gl" attrs []
5 Likes