0

My actual problem is much more specific, but I think a more general answer will help me to cope with future needs.

I actually need to enable leaflet-extras plugin for leaflet underlying pyqtlet.

Documentation says:

Download leaflet-providers.js and include it in your page after including Leaflet, e.g.:

<head>
  ...
  <script src="http://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <script src="js/leaflet-providers.js"></script>
</head>

and then:

// add Stamen Watercolor to map.
L.tileLayer.provider('Stamen.Watercolor').addTo(map);

Of course all this is in the assumption you are writing a JavaScript app while I am in pyqtlet environment.

I tried to cope in a very ugly way:

  • downloaded leaflet-providers.js to my venv/lib/python3.8/site-packages/pyqtlet/web/modules
  • added the line <script src="modules/leaflet-providers.js"></script> to my venv/lib/python3.8/site-packages/pyqtlet/web/map.html
  • used self.map.runJavaScript("L.tileLayer.provider('Stamen.Watercolor'). addTo(map)") to activate the desired tileLayer

This actually works, but I'm sure there's a cleaner way to achieve the same.

Any hint welcome.

ZioByte
  • 2,690
  • 1
  • 32
  • 68

1 Answers1

2

A trivial solution is to read the .js and run it:

with open("/path/of/leaflet-providers.js") as f:
    self.map.runJavaScript(f.read())
    self.map.runJavaScript("L.tileLayer.provider('Stamen.Watercolor'). addTo(map)")

Another similar option is to use document.createElement:

with open("/path/of/leaflet-providers.js") as f:
    code = f.read()
    SCRIPT = """
    const script = document.createElement('script');
    script.type = 'text/javascript';
    document.head.appendChild(script);
    script.text = `%s`;
    """ % (
        code,
    )
    self.map.runJavaScript(SCRIPT)
    self.map.runJavaScript(
        "L.tileLayer.provider('Stamen.Watercolor'). addTo(map)"
    )

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks. With first solution (seems simpler) will I have javascript code loaded? I mean: if I later need to use the same plugin again can I just `self.map.runJavaScript("L.tileLayer.provider('Another.choice'). addTo(map)")` or do I need to read the `leaflet-providers.js` again? – ZioByte Oct 24 '21 at 14:26
  • @ZioByte I haven't tested it but you probably don't have to upload it, test and verify. The second option I think could not have that drawback, both are simple ways, there is nothing magical. – eyllanesc Oct 24 '21 at 14:28