使用Python“runJavascript”输入更新Goole Maps Marker位置

时间:2018-02-15 01:05:18

标签: javascript python google-maps-markers pyqt5 qwebengineview

我正在尝试使用PyQt5创建一个简单的应用程序,我想显示一个谷歌地图网页。 我想在地图上显示一个标记,该标记取决于用户在python中修改的一些变量。 如何使用runJavascript

执行此操作

这是html文件:

<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>

这里是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

这里是Python代码:

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_())

我正在考虑以这种方式修改Html文件中的Initialize函数:

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

然后传递Python代码中的坐标:

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

但这似乎不起作用。如何访问Initialize函数并输入坐标?

1 个答案:

答案 0 :(得分:1)

您必须注释以下行,因为它在加载应用时调用该函数:

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

您必须在页面加载页面时调用该函数:

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))