1

I am trying to create a simple app with PyQt5 and I want to show a google map web page. I would like to show a marker that appear on the map in a location that depends on some variables modified by the user in python. How can I do that using runJavascript?

here is the html file:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

 function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('info').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function updateMarkerAddress(str) {
  document.getElementById('address').innerHTML = str;
}


var geocoder = new google.maps.Geocoder();
var map;


function initialize() {
  var latLng = new google.maps.LatLng(40.767367, -111.848007);
  map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 11,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
    var marker = new google.maps.Marker({
    position: latLng,
    title: 'Point A',
    map: map,
    draggable: true
  });

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);

  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });

  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });

  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
  });

//  return latLng
}


// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>
<body>
  <style>
  #mapCanvas {

    # width: 1000px;
    width: 102%;
    height: 500px;
    float: left;
    margin-left: -7px;
    margin-right: -10px;
    margin-top: -7px;
    margin-bottom: 10px;
  }
  #infoPanel {
    float: center;
    margin-left: 20px;
  }
  #infoPanel div {
    margin-bottom: 10px;
  }
  </style>

      <font size="3" color="black" face="verdana">
  <div id="mapCanvas"></div>
  <div id="infoPanel">
    <font size="3" color="black" face="verdana">
    <!-- <b>Marker status:</b> -->
    <div id="markerStatus"><i>Click and drag the marker.</i></div>
    <font size="3" color="black" face="verdana">
    <b>Current position:</b>
    <div id="info"></div>
    <!--<b>Closest matching address:</b>-->
    <!--<div id="address"></div>-->
  </div>
</body>
</html>

Here the PyQt5 gui:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_tmy3page(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(900, 620)
        MainWindow.setMinimumSize(QtCore.QSize(900, 620))
        MainWindow.setMaximumSize(QtCore.QSize(900, 620))
        MainWindow.setWindowTitle("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.html_code = QtWebEngineWidgets.QWebEngineView(self.centralwidget)
        self.html_code.setGeometry(QtCore.QRect(0, 0, 901, 621))
        self.html_code.setUrl(QtCore.QUrl("about:blank"))
        self.html_code.setObjectName("html_code")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass

from PyQt5 import QtWebEngineWidgets

And here the Python code:

import sys
from PyQt5.QtWidgets import *
from GUI_tmy3 import *

class ShowMap_fun(QMainWindow):
    def __init__(self):
        super().__init__()
        self.map_ui = Ui_tmy3page()
        self.map_ui.setupUi(self) 
     self.map_ui.html_code.load(QtCore.QUrl.fromLocalFile(QtCore.QDir.current().filePath("useless.html")))



if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ShowMap_fun()
    ex.show()
    sys.exit(app.exec_())

I was thinking to modify the Initialize function in the Html file this way:

function initialize(lat_init, long_init)
{
var latLng = new google.maps.LatLng(lat_init, long_init);

And then pass the coordinates from the Python code:

argument_init = "initialize('" + str(40) + "','" + str(-111) + "')"
self.map_ui.html_code.page().runJavaScript(argument_init)

But this doesn't seem to work. How can I access the Initialize function and input the coordinates?

Carlo Bianchi
  • 115
  • 4
  • 15

1 Answers1

1

You must comment the following line since it calls that function at the time of loading the app:

// Onload handler to fire off the app.
//google.maps.event.addDomListener(window, 'load', initialize);

You must also call the function when the page finishes loading the page:

class ShowMap_fun(QMainWindow):
    def __init__(self):
        super().__init__()
        self.map_ui = Ui_tmy3page()
        self.map_ui.setupUi(self) 
        self.map_ui.html_code.load(QtCore.QUrl.fromLocalFile(QtCore.QDir.current().filePath("useless.html")))

        argument_init = "initialize('" + str(40) + "','" + str(-111) + "')"
        self.map_ui.html_code.loadFinished.connect(
            lambda ok: self.map_ui.html_code.page().runJavaScript(argument_init))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241