0

In my PyQt app I want to show a leaflet map. The code works fine with online tiles but what I want to do is to show the map offline and for this I have downloaded some tiles for an area using Mobile Atlas Creator, here is how to do that. If I open html file in browser the map works fine however it's not working in PyQt app.

main.py

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        browser = QWebEngineView()
        html = open('index.html', 'r').read()
        browser.setHtml(html)
        vbox = QVBoxLayout()
        hBox = QVBoxLayout()
        hBox.addWidget(browser)
        vbox.addLayout(hBox)
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layout.addLayout(vbox)
        self.setCentralWidget(widget)

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    return app.exec_()


if __name__ == '__main__':
    sys.exit(main())

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaflet Map</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />     
</head>
<body>
    <div id="map" style="height: 100vh; width: 100%;"></div>
</body>
</html>

<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script>

    var loc = [48.85628846134472, 2.2929097921857955]
    var map = L.map('map').setView(loc, 16);

    // this work
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    // this dose'nt work
    L.tileLayer('img/{z}/{x}/{y}.png', { maxZoom: 18  }).addTo(map);
   
</script>
Mohammad
  • 55
  • 2
  • 7
  • Your `index.html` still depends on online CSS files (e.g. ``). Can you download those and use local copies? – kwsp Mar 04 '22 at 21:27
  • @kwsp Yes I can. But right now it doesn't matter. I just want to show my downloaded tiles – Mohammad Mar 04 '22 at 21:37
  • 1
    I see. Notice that `L.tileLayer` takes a URL as a parameter, so you need to pass in the local URL of that PNG file. I'm not familiar with QWebEngineView, but have you looked into how it loads local resources? A starting point might be https://doc-snapshots.qt.io/qt6-6.3/qwebenginenavigationrequest.html – kwsp Mar 04 '22 at 22:34
  • @kwsp Thank you. It worked! I had to pass the the path like `"file:///D:/path/to/{z}/{x}/{y}.png"` – Mohammad Mar 05 '22 at 06:24

0 Answers0