c++ QWebEngineView应用无法加载Google Maps API,js:Uncaught(in promise)错误:无法加载Google Maps JavaScript API

dgiusagp  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(367)

我有一个在QWebEngineView中显示GoogleMap的应用程序。该应用程序在Windows上运行良好,但到目前为止,我还没有成功地让应用程序在Ubuntu或MacOS上运行。为了缩小问题,我修改了Qt Map Example以复制错误。这个测试应用程序是在Qt版本6.4.1上编译的。GCC++编译器是版本11.04。

maps.pro:

TEMPLATE = app

QT += webenginewidgets widgets

HEADERS += \
    mainwindow.h

SOURCES += main.cpp \
    mainwindow.cpp

CONFIG+=use_gold_linker

target.path = $$[QT_INSTALL_EXAMPLES]/webenginewidgets/maps
INSTALLS += target

字符串

main.cpp

// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QCoreApplication::setOrganizationName("QtExamples");
    QApplication app(argc, argv);

    MainWindow mainWindow;
    mainWindow.resize(1024, 768);
    mainWindow.show();

    return app.exec();
}

mainwindow.h

// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWebEngineView>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);

private:
    QWebEngineView *m_view;
};

#endif // MAINWINDOW_H

主窗口.cpp

// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "mainwindow.h"

#include <QMessageBox>
#include <QDir>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_view(new QWebEngineView(this))
{
    setCentralWidget(m_view);

    QWebEnginePage *page = m_view->page();

    QFileInfo info(QDir::currentPath() + QDir::separator() + "test.htm");
    if(info.exists())
       page->load(QUrl::fromLocalFile(info.filePath()));
       //page->load(QUrl("https://googlemaps.com"));
}

apikey.js //包含有效的apikey

var apikey2  = "APIKEY"; // API key 3
console.log("api keys loaded");

test.htm //主窗口.cpp加载的html文件:

<html>
  <head>
  <meta name="viewport" content="initial-scale=1.0" user-scalable="yes" />
  <style type="text/css">
    html { height: 100%; }
    body { height: 100%; margin: 0; padding: 0 }
    #map { height: 100%; }
    .menu {
        width: 160px;
        box-shadow: 3px 3px 5px #888888;
        border-style: solid;
        border-width: 1px;
        border-color: grey;
        border-radius: 2px;
        background-color: #ffff;
        position: fixed;
        text-align: center;
        display: none;
    }

    .menu-item {
        height: 20px;
        background-color: white;
    }
</style>
<title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- playground-hide -->
    <script src="apikey.js"> </script>
    <script>
      const process = { env: {} };
      process.env.GOOGLE_MAPS_API_KEY =
        apikey2;
    </script>
    <!-- playground-hide-end -->

    <!--link rel="stylesheet" type="text/css" href="./style.css" /-->
    <script type="module" src="./test_index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: apikey2, v: "weekly"});</script>
  </body>
</html>

test_index.js //JavaScript模块

let map; //google.maps.Map;
async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");
  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });

  console.log("initMap done");
}

initMap();
//export {};


运行程序会导致空白屏幕和以下错误:

19:15:35: Debugging /home/allen/Projects/build-maps-Desktop_Qt_6_4_1_GCC_64bit-Debug/maps ...
qt.webenginecontext: 

GL Type: desktop
Surface Type: OpenGL
Surface Profile: CompatibilityProfile
Surface Version: 4.3
QSG RHI Backend: OpenGL
Using Supported QSG Backend: yes
Using Software Dynamic GL: no
Using Multithreaded OpenGL: yes

Init Parameters:
  *  application-name maps 
  *  browser-subprocess-path /home/allen/Qt/6.4.1/gcc_64/libexec/QtWebEngineProcess 
  *  create-default-gl-context  
  *  disable-features ConsolidatedMovementXY,InstalledApp,BackgroundFetch,WebOTP,WebPayments,WebUSB,PictureInPicture 
  *  disable-setuid-sandbox  
  *  disable-speech-api  
  *  enable-features NetworkServiceInProcess,TracingServiceInProcess 
  *  enable-threaded-compositing  
  *  in-process-gpu  
  *  use-gl desktop 

js: Uncaught (in promise) Error: The Google Maps JavaScript API could not load.
23:38:02: Debugging of /home/allen/Projects/build-maps-Desktop_Qt_6_4_1_GCC_64bit-Debug/maps has finished with exit code 0.

ssgvzors

ssgvzors1#

问题原来是QWebEngineView不会从本地文件加载页面。我添加了一个qrc资源文件,其中包含test.htm和test_index.js,然后更改了行

page->load(QUrl::fromLocalFile(info.filePath()));

字符串

page->load("qrc:/test.htm");


纠正了这个问题。

相关问题