python - PyQt 5.9 中的 OpenLayers 地理定位

标签 python pyqt openlayers pyqt5 qwebengineview

我已经实现了一个带有地理定位功能和按钮的网站。

该网页在 QwebEngineView(OSM map 也是如此)中显示良好。 网页已加载

def __init__(self, parent=None):
        super(MainGUI, self).__init__(parent)
        self.ui = uic.loadUi("GPS.ui", self)
        self.ui.w3View.load(QtCore.QUrl('file:///Map.html'))

所有 native OpenLayers 按钮(放大和缩小)都工作正常。

我创建了一个新的自定义按钮来在 OpenLayers map 上显示我的地理位置。

这是我用来对我进行地理定位的函数:

var handleGeolocation = function() {

      var coordinates;
      var geolocation = new ol.Geolocation({
        projection: view.getProjection(),
        tracking: true
      });
      // handle geolocation error.
      geolocation.on('error', function (error) {
        var info = document.getElementById('info');
        info.innerHTML = error.message;
        info.style.display = '';
      });

      var accuracyFeature = new ol.Feature();
      geolocation.on('change:accuracyGeometry', function () {
        accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
      });

      var positionFeature = new ol.Feature();
      positionFeature.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 6,
          fill: new ol.style.Fill({
            color: '#3399CC'
          }),
          stroke: new ol.style.Stroke({
            color: '#fff',
            width: 2
          })
        })
      }));

      geolocation.once('change:position', function () {
        coordinates = geolocation.getPosition();
        positionFeature.setGeometry(coordinates ?
          new ol.geom.Point(coordinates) : null);
        map.getView().setCenter(coordinates);
        map.getView().setZoom(17);
      });

      new ol.layer.Vector({
        map: map,
        source: new ol.source.Vector({
          features: [accuracyFeature, positionFeature]
        })
      });
    }

我在 here 的帮助下创建了按钮.

整个网页如下所示:

<!DOCTYPE html>
<html>
  <head>
    <title>Accessible Map</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.2.0/build/ol-debug.js"></script>
   <style>
      a.skiplink {
        position: absolute;
        clip: rect(1px, 1px, 1px, 1px);
        padding: 0;
        border: 0;
        height: 1px;
        width: 1px;
        overflow: hidden;
      }
      a.skiplink:focus {
        clip: auto;
        height: auto;
        width: auto;
        background-color: #fff;
        padding: 0.3em;
      }
      #map:focus {
        outline: #4A74A8 solid 0.15em;
      }
      map{
          max-width: 760 px;
          max-height: 50 px;
      }

      .geoButton {
        top: 80px;
        left: .5em;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map" tabindex="0"></div>
    <script>
      window.app = {};
      var app = window.app;


      view = new ol.View({
        center: [0, 0],
        zoom: 2
      });

      app.getLocation = function(opt_options) {
        var options = opt_options || {};

        var geoButton = document.createElement('button');
        geoButton.innerHTML = 'L';

        var handleGeolocation = function() {
          /*    var isMobile =  {
              Android: function () {
                return navigator.userAgent.match(/Android/i);
              },
              BlackBerry: function () {
                return navigator.userAgent.match(/BlackBerry/i);
              },
              iOS: function () {
                return navigator.userAgent.match(/iPhone|iPod|iPad/i);
              },
              Opera: function () {
                return navigator.userAgent.match(/Opera Mini/i);
              },
              Windows: function () {
                return navigator.userAgent.match(/IEMobile/i);
              },
              any: function () {
                return ((isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()));
              }
            };

            if (isMobile.any()){
              geolocation.setTrackingOptions(enableHighAccuracy );
            } */

          var coordinates;
          var geolocation = new ol.Geolocation({
            projection: view.getProjection(),
            tracking: true
          });
          // handle geolocation error.
          geolocation.on('error', function (error) {
            var info = document.getElementById('info');
            info.innerHTML = error.message;
            info.style.display = '';
          });

          var accuracyFeature = new ol.Feature();
          geolocation.on('change:accuracyGeometry', function () {
            accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
          });

          var positionFeature = new ol.Feature();
          positionFeature.setStyle(new ol.style.Style({
            image: new ol.style.Circle({
              radius: 6,
              fill: new ol.style.Fill({
                color: '#3399CC'
              }),
              stroke: new ol.style.Stroke({
                color: '#fff',
                width: 2
              })
            })
          }));

          geolocation.once('change:position', function () {
            coordinates = geolocation.getPosition();
            positionFeature.setGeometry(coordinates ?
              new ol.geom.Point(coordinates) : null);
            map.getView().setCenter(coordinates);
            map.getView().setZoom(17);
          });

          new ol.layer.Vector({
            map: map,
            source: new ol.source.Vector({
              features: [accuracyFeature, positionFeature]
            })
          });
        }

        geoButton.addEventListener('click', handleGeolocation, false);
        geoButton.addEventListener('touchstart', handleGeolocation, false);

        var element = document.createElement('div');
        element.className = 'ol-unselectable ol-control geoButton';
        element.appendChild(geoButton);

        ol.control.Control.call(this, {
          element: element,
          target: options.target
        });

      };

      ol.inherits(app.getLocation, ol.control.Control);
      //Standard Initialisierung


      // Geolocation function



      var map = new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        controls: ol.control.defaults({
          attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            collapsible: false
          })
        }).extend([new app.getLocation()]),
        view: view
      });

      //Display Input Datastream
    </script>
  </body>
</html>

在普通浏览器中它工作正常,但在我的 PyQt 应用程序中却不行。 单击自定义按钮后没有任何反应。

我做错了什么或者不可能吗?

最佳答案

主要问题是启用权限,如果您在Firefox、Chrome等浏览器中运行,会弹出一个窗口,询问您是否接受GeoLocation权限。

在这种情况下,它必须通过代码启用,为此,每次需要授权时,QWebEnginePage 都会发出一个信号,它通过信号 featurePermissionRequested 来执行此操作。 ,我们将其连接到某个插槽,并使用函数 setFeaturePermission() 启用权限。 .

    self.ui.w3View..page().featurePermissionRequested.connect(self.onFeaturePermissionRequested)

def onFeaturePermissionRequested(self, securityOrigin, feature):
    self.sender().setFeaturePermission(securityOrigin,
                                     QWebEnginePage.Geolocation,
                                     QWebEnginePage.PermissionGrantedByUser)

注意:在 Linux 上,我仍然遇到 Geoclue 提供程序的问题,错误消息如下:

Failed to set Geoclue positioning requirements. Geoclue error: org.qtproject.QtDBus.Error.InvalidObjectPath

关于python - PyQt 5.9 中的 OpenLayers 地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689597/

相关文章:

python - Django:显示Person模型的属性

database - PyQt 在 TableView 中加载数据库

javascript - 将 OpenLayers map 作为 SVG foreignObject 嵌入会导致 map 出现在所有其他 SVG 元素之上,而不管 SVG 元素顺序如何

javascript - 使用 GeoWebCache 时出现“粉红色瓷砖”

qt - 在 Windows 上 setRange(0, 0) 时将文本放在 QProgressBar 的中间?

javascript - 如何在 OpenLayers 2 中启用街景控件?

python - 如何将 Kivy 触摸坐标转换为小部件空间

python - Python 中的日期时间触发器?

python - 按范围扩展 DataFrame

python - 适用于 OSX 10.6 上 PyQt 的 Qt 设计器