SimonDanisch / Bonito.jl

Serving JS to the browser
MIT License
204 stars 29 forks source link

notify not work in Leaflet jsrender #240

Closed kongdd closed 1 month ago

kongdd commented 1 month ago
using Bonito, Observables
using Markdown

leafletjs = Bonito.ES6Module("https://esm.sh/v133/leaflet@1.9.4/es2022/leaflet.mjs")
leafletcss = Bonito.Asset("https://unpkg.com/leaflet@1.9.4/dist/leaflet.css")

struct LeafletMap
    position::NTuple{2,Float64} # lat, lon
    zoom::Int
end

lon = Observable(0.0)
lat = Observable(0.0)

onany(lat, lon) do lat, lon
    println("lat: ", lat, " lon: ", lon)
end

function Bonito.jsrender(session::Session, map::LeafletMap)
    title = md"""
    # Hello world!
    """

    map_div = DOM.div(; id="map", style="height: 500px;")
    coords_label = DOM.div("POI"; id="coords")

    map_js = js"""
      $(leafletjs).then(L => {
          const map = L.map('map').setView($(map.position), $(map.zoom));
          L.tileLayer(
              'https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
              maxZoom: 19,
              attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
          }).addTo(map);

          // Add click event listener
          map.on('click', function(e) {
              var lat = e.latlng.lat;
              var lon = e.latlng.lng;

              $(lat).notify(lat)
              $(lon).notify(lon)

              console.log("lon:" + lon);
              console.log("lon:" + lat);

              const coordsDiv = document.getElementById('coords');
              coordsDiv.innerHTML = '(lat, lon): ' + lat.toFixed(6) + ', ' + lon.toFixed(6);
              // Optionally, you can do other things with these coordinates
          });
      })
    """
    return Bonito.jsrender(
        session, DOM.div(leafletcss, leafletjs, title, map_div, coords_label, map_js)
    )
end

page_leaf = App() do
    point = (30.460452, 114.612594)
    return LeafletMap(point, 13)
end
kongdd commented 1 month ago

Sorry. solved.

kongdd commented 1 month ago

Hi @SimonDanisch, Could you give some guide about how to wrap js file? I am trying to put the map click function into a separate js file. But failed.

SimonDanisch commented 1 month ago

You should do it like this: https://github.com/MakieOrg/Makie.jl/blob/master/WGLMakie/src/WGLMakie.jl#L34 https://github.com/MakieOrg/Makie.jl/blob/master/WGLMakie/src/three_plot.jl#L43-L61 https://github.com/MakieOrg/Makie.jl/blob/master/WGLMakie/src/wglmakie.js#L432-L444

kongdd commented 1 month ago

Thank you, solved. The final script is at https://github.com/jl-pkgs/ABC_Bonito.jl/blob/main/page_leaflet.jl.