Igor-Vladyka / leaflet.browser.print

A leaflet plugin which allows users to print the map directly from the browser
https://igor-vladyka.github.io/leaflet.browser.print/
MIT License
154 stars 76 forks source link

Legend disappear when print ends #123

Closed AlbertoMCS closed 1 year ago

AlbertoMCS commented 1 year ago

Hi Igor, I hope you are very well. I have an issue with the plugging. I created a control to contain a legend. I can print and the legend is showed in the pdf, so all good. The problem comes when the print ends, as the legend is not showed anymore in my map. When clicking on the print button again I got this error:

leaflet.js:5 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at ci (leaflet.js:5:18727)
    at i.addTo (leaflet.js:5:46514)
    at i.<anonymous> (Tryintel_March.php:3372:49)
    at i.fire (leaflet.js:5:5014)
    at i._print (leaflet.browser.print.js:238:13)
    at i._printLandscape (leaflet.browser.print.js:44:8)
    at i._printMode (leaflet.browser.print.js:194:29)
    at i.eval (leaflet.browser.print.modes.js:57:25)
    at HTMLUListElement.c (leaflet.js:5:21764)

Here my code:

HTML (content of the legend)

    <div id="legend">
      <div id="CycleLegendRoutes">
        <!-- //to be dinamically appended -->
      </div>
      <div id="CycleLegendTraffic">
        <div id="CycleLegendTrafficOnraod">
          <svg height="15" width="10"><line id= "cycleLineAttributesOnroadLegend" class= "cycleLineAttributes" x1="0" y1="7.5" x2="10" y2="7.5" style="stroke:rgb(160,32,240);stroke-width:4" /></svg>On Road
        </div>
      </div>
    </div>

JS

  L.control.browserPrint({
      position:'topright',
      dpi:300,
  }).addTo(mymap)

  L.Control.Mylegend = L.Control.extend({
    onAdd: function (mymap) {
    var div = document.getElementById("legend");
    return div;
    }
  });

  L.controlmylegend = function(opts) {
    return new L.Control.Mylegend(opts);
  }

  L.controlmylegend({ position: 'bottomright' }).addTo(mymap);

  mymap.on("browser-print-start", function(e){
    L.controlmylegend({position: 'bottomright'}).addTo(e.printMap);
  });

Many thanks!

AlbertoMCS commented 1 year ago

I managed to fix it by changing onAdd

  L.Control.Mylegend = L.Control.extend({
    onAdd: function (mymap) {
    var div = L.DomUtil.create('div', 'info legend-leaflet')
    div.innerHTML = document.getElementById("legend").innerHTML
    return div;
    }
  });