使用python 3使用PyQt4 QWebView查看地图 [英] Viewing maps with PyQt4 QWebView using python 3

查看:102
本文介绍了使用python 3使用PyQt4 QWebView查看地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个程序,该程序可以根据数据库中的特定坐标显示带有标记的地图,因此过程是:

I am building a program that can show a map with a markers according to specific coordinates from a database, so the process is:

  1. 使用(folium)从osm获取地图
  2. 添加标记
  3. 将地图另存为HTML
  4. 在QWebView中显示map.html.

但是,如果坐标始终在变化,例如(车辆跟踪系统),则这种方法不切实际.

But this way is not practical if the coordinates are always changing e.g(vehicles tracking system).

无论如何,是否可以避免在前面的过程中添加或更新地图上的标记,而无需创建map.html文件,然后将其加载到QWebView中,然后每次都显示它.

Is there anyway that could allow me to add or update markers on the map avoiding the previous process, without having to create the map.html file then load it to QWebView then showing it every time .

谢谢

推荐答案

前一段时间,我创建了一个小图书馆,使用PyQt和 OpenStreetMap ,因为您的问题,我添加了此功能因此您可以从链接下载代码,然后尝试示例:qOSMExample2.py

Some time ago I had created a small library to show markers in maps using PyQt and Google Maps or OpenStreetMap, because of your question I added this functionality so you can download the code from this link and try the example: qOSMExample2.py

在此答案中,我将向您展示代码中最重要的部分,以便您可以添加自定义功能.

In this answer I'll show you the most important parts of my code so that you can add custom functionality.

QWebView支持javascript,因此我使用了传单库,它包含在html中,如下所示:

QWebView supports javascript so I used the leaflet library, and this is included in the html as shown below:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>


    <style type="text/css">
			html { height: 100%; }
			body { height: 100%; margin: 0; padding: 0 }
			#mapid { height: 100% }
    </style>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"
          integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ=="
          crossorigin=""/>

    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"
            integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg=="
            crossorigin=""></script>

    <script type="text/javascript" src="qOSM.js"></script>
</head>
<body onload="initialize()">
<div id="mapid" style="width:100%; height:100%"></div>
</body>
</html>

此外,如果我们观察到,我导入了 qOSM.js 文件,该文件实现了创建,移动地图以及带有标记的逻辑.

In addition if we observe I have imported the qOSM.js file that implements the logic of creating, moving the map and the same with the markers.

另一个重要的是将python与javascript进行交互pyqt为我们提供了2个功能:

The other important is to interact python with javascript for it pyqt offers us 2 functions:

无效QWebFrame :: addToJavaScriptWindowObject(const QString& name,QObject * object)

在框架的JavaScript中使用名称使对象可用 语境.该对象将作为框架窗口的子级插入 目的. [...]

Make object available under name from within the frame's JavaScript context. The object will be inserted as a child of the frame's window object. [...]

self.page().mainFrame().addToJavaScriptWindowObject("qtWidget", self)

QVariant QWebFrame :: evaluateJavaScript(const QString& amp; scriptSource)

使用以下框架评估scriptSource定义的JavaScript: 上下文,并返回最后执行的语句的结果.

Evaluates the JavaScript defined by scriptSource using this frame as context and returns the result of the last executed statement.

def runScript(self, script):
    return self.page().mainFrame().evaluateJavaScript(script)

第一个功能允许我们在js中嵌入python对象,因此我们可以从js输出信号并将它们连接到python插槽.第二个面向执行js函数并接收返回的内容.总之,第一个用于异步获取答案,第二个用于异步获取答案.

The first function allows us to embed a python object in js and so we can output signals from js and connect them to python slots. The second is oriented to execute functions of js and receive what returns. In summary the first one serves to obtain answers asynchronously and the second one synchronously.

在下一部分中,我展示了实现上述功能的js:

In the next part I show the js where the functions mentioned above are implemented:

// Where you want to render the map.

var map;

var markers = [];

var LeafIcon;

function initialize() {
    var element = document.getElementById('mapid');

    map = L.map(element);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    if (typeof qtWidget !== 'undefined') {

        map.on('dragend', function () {
            center = map.getCenter();
            qtWidget.mapMoved(center.lat, center.lng);
        });

        map.on('click', function (ev) {
            qtWidget.mapClicked(ev.latlng.lat, ev.latlng.lng);
        });

        map.on('dblclick', function (ev) {
            qtWidget.mapDoubleClicked(ev.latlng.lat, ev.latlng.lng);
        });

        map.on('contextmenu', function (ev) {
            qtWidget.mapRightClicked(ev.latlng.lat, ev.latlng.lng);
        });
    }

    LeafIcon = L.Icon.extend({
        options: {
            shadowUrl: 'leaf-shadow.png',
            iconSize: [38, 95],
            shadowSize: [50, 64],
            iconAnchor: [22, 94],
            shadowAnchor: [4, 62],
            popupAnchor: [-3, -76]
        }
    });
}

function osm_setCenter(lat, lng) {
    //console.log(lat);
    map.panTo(new L.LatLng(lat, lng));
}

function osm_getCenter() {
    return map.getCenter();
}

function osm_setZoom(zoom) {
    map.setZoom(zoom);
}

function osm_addMarker(key, latitude, longitude, parameters) {

    if (key in markers) {
        osm_deleteMarker(key);
    }

    if ("icon" in parameters) {

        parameters["icon"] = new L.Icon({
            iconUrl: parameters["icon"],
            iconAnchor: new L.Point(16, 16)
        });
    }

    var marker = L.marker([latitude, longitude], parameters).addTo(map);

    if (typeof qtWidget !== 'undefined') {

        marker.on('dragend', function (event) {
            var marker = event.target;
            qtWidget.markerMoved(key, marker.getLatLng().lat, marker.getLatLng().lng);
        });

        marker.on('click', function (event) {
            var marker = event.target;
            //marker.bindPopup(parameters["title"]);
            qtWidget.markerClicked(key, marker.getLatLng().lat, marker.getLatLng().lng);
        });

        marker.on('dbclick', function (event) {
            var marker = event.target;
            qtWidget.markerClicked(key, marker.getLatLng().lat, marker.getLatLng().lng);
        });

        marker.on('contextmenu', function (event) {
            var marker = event.target;
            qtWidget.markerRightClicked(key, marker.getLatLng().lat, marker.getLatLng().lng);
        });
    }

    markers[key] = marker;
    return key;
}

function osm_deleteMarker(key) {
    map.removeLayer(markers[key]);
    delete markers[key];
}

function osm_moveMarker(key, latitude, longitude) {
    marker = markers[key];
    var newLatLng = new L.LatLng(latitude, longitude);
    marker.setLatLng(newLatLng);
}

function osm_posMarker(key) {
    marker = markers[key];
    return [marker.getLatLng().lat, marker.getLatLng().lng];
}


http://

输出:

这篇关于使用python 3使用PyQt4 QWebView查看地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆