Qt加载百度地图步骤
1.在百度地图开放平台申请密钥。申请地址:http:
2.使用Qt控件QWebEngineView进行加载百度地图html文件
3.将Qt自己的qwebchannel.js从安装包中找到拷贝到自己的工程中,注意一定要和html放在同一个目录下
具体效果如下:

百度地图html文件内容
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>CanvasLayer</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?type=webgl&v=3.0&ak=您自己的密钥"></script>
<!-- <script type="text/javascript" src="http://api.map.baidu.com/api?type=webgl&v=3.0&ak=DUcoOOGEL6vt1ghHWaTSNr9BBykVhUnA"></script> -->
<style type="text/css">
body, html,#container {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
<script src="qwebchannel.js"></script>
<script type="text/javascript">
var map = new BMapGL.Map("container");
map.centerAndZoom(new BMapGL.Point(116.3964,39.9093), 12);
map.enableScrollWheelZoom(true);
new QWebChannel(qt.webChannelTransport, function(c) {
mw = c.objects.window;
});
map.addEventListener("click",function(e){
mw.onRecvPostion(e.latlng.lng,e.latlng.lat);
});
function SetPoint(lng,lat){
map.setCenter(new BMapGL.Point(lng,lat));
}
function currentCity()
{
function getCityName(result)
{
var cityName = result.name;
mw.mapToWin(cityName);
}
var city = new BMapGL.LocalCity();
city.get(getCityName);
}
function Location()
{
var geolocation = new BMapGL.Geolocation();
geolocation.enableSDKLocation();
geolocation.getCurrentPosition(function(r)
{
if(this.getStatus() == BMAP_STATUS_SUCCESS)
{
var mk = new BMapGL.Marker(r.point);
map.addOverlay(mk);
map.panTo(r.point);
}
else
{
alert("failed" + this.getStatus());
}
});
}
function SetCarPlanPath(startLng, startLat, endLng, endLat)
{
var p1 = new BMapGL.Point(startLng, startLat);
var p2 = new BMapGL.Point(endLng, endLat);
var driving = new BMapGL.DrivingRoute(map, {renderOptions:{map:map, autoViewport:true}});
driving.search(p1, p2);
}
</script>
Qt工程:
.h文件内容
#pragma once
#include <QMainWindow>
#include <QWebEngineView>
#include <QLineEdit>
#include "AddressToPosition.h"
class Channel;
class MapWidget : public QMainWindow
{
Q_OBJECT
public:
explicit MapWidget(QWidget* parent = nullptr);
void setCurrentCityName(const QString);
private:
void initWin();
private slots:
void onChannelPos(QString f, QString l);
void onLocation();
void onSearch();
void onCurrentCityName(QString name);
private:
QScopedPointer<QWebEngineView> m_pWebView;
QScopedPointer<AddressToPosition> m_pAddress;
QLineEdit* m_pStartLocation;
QLineEdit* m_pEndLocation;
Channel* m_pChannel;
QString m_CurrentName;
};
class Channel : public QObject
{
Q_OBJECT
public:
explicit Channel(QObject* parent = nullptr);
void currentCityName(QString& cityName);
signals:
void sigCurrentPostion(const QString, const QString);
void sigCurrentCityName(const QString cityName);
public slots:
void onRecvPostion(const QString, const QString);
void mapToWin(const QString cityName);
private:
QString m_currentCityName;
};
.cpp文件内容
#include "MapWidget.h"
#include <QWebChannel>
#include <QLayout>
#include <QStatusBar>
#include <QMenuBar>
#include <QToolButton>
MapWidget::MapWidget(QWidget* parent)
: QMainWindow(parent)
, m_pWebView(new QWebEngineView(this))
, m_pAddress(new AddressToPosition())
{
this->initWin();
}
void MapWidget::initWin()
{
m_pChannel = new Channel(this);
connect(m_pChannel, &Channel::sigCurrentPostion, this, &MapWidget::onChannelPos);
connect(m_pChannel, &Channel::sigCurrentCityName, this, &MapWidget::onCurrentCityName);
QWebChannel* pWebChannel = new QWebChannel(this);
pWebChannel->registerObject("window", (QObject*)m_pChannel);
this->m_pWebView->page()->setWebChannel(pWebChannel);
this->m_pWebView->page()->load(QUrl("qrc:/html/map/BDMap.html"));
m_pStartLocation = new QLineEdit();
m_pStartLocation->setPlaceholderText(QStringLiteral("开始位置"));
m_pEndLocation = new QLineEdit();
m_pEndLocation->setPlaceholderText(QStringLiteral("结束位置"));
QToolButton* pSearch = new QToolButton();
pSearch->setText(QStringLiteral("搜索"));
connect(pSearch, &QToolButton::clicked, this, &MapWidget::onSearch);
QToolButton* pLocationBut = new QToolButton(m_pWebView.data());
pLocationBut->setFixedSize(30, 30);
pLocationBut->setText(QStringLiteral("定位"));
connect(pLocationBut, &QToolButton::clicked, this, &MapWidget::onLocation);
QVBoxLayout* pSearchLayout = new QVBoxLayout();
pSearchLayout->addWidget(pLocationBut, 0, Qt::AlignBottom);
QHBoxLayout* pViewLayout = new QHBoxLayout();
pViewLayout->addStretch(1);
pViewLayout->addLayout(pSearchLayout, 0);
this->m_pWebView->setLayout(pViewLayout);
QHBoxLayout* pRightLayout = new QHBoxLayout();
pRightLayout->addWidget(m_pStartLocation, 1);
pRightLayout->addWidget(m_pEndLocation, 1);
pRightLayout->addWidget(pSearch);
QWidget* pMainWidget = new QWidget();
QVBoxLayout* pMainLayout = new QVBoxLayout();
m_pWebView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
pMainLayout->addWidget(m_pWebView.data(),1);
pMainLayout->addLayout(pRightLayout);
pMainWidget->setLayout(pMainLayout);
this->setCentralWidget(pMainWidget);
}
void MapWidget::onChannelPos(QString f, QString l)
{
this->statusBar()->showMessage(QString("%1,%2").arg(f).arg(l), 1500);
this->m_pWebView->page()->runJavaScript(QString("SetPoint(%1,%2)").arg(f).arg(l));
}
void MapWidget::onLocation()
{
this->m_pWebView->page()->runJavaScript(QString("Location()"));
}
void MapWidget::onSearch()
{
this->m_pWebView->page()->runJavaScript(QString("currentCity()"));
}
void MapWidget::onCurrentCityName(QString cityName)
{
if (m_pAddress == nullptr)return;
m_pAddress->setCurrentCityName(cityName);
QString startLocat = m_pStartLocation->text();
QString endLocat = m_pEndLocation->text();
m_pAddress->onAddressRequest(startLocat);
std::tuple<double, double> startInfo;
m_pAddress->locatCoord(startInfo);
m_pAddress->onAddressRequest(endLocat);
std::tuple<double, double> endInfo;
m_pAddress->locatCoord(endInfo);
this->m_pWebView->page()->runJavaScript(QString("SetCarPlanPath(%1,%2,%3,%4)").arg(std::get<0>(startInfo)).arg(std::get<1>(startInfo)).arg(std::get<0>(endInfo)).arg(std::get<1>(endInfo)));
}
Channel::Channel(QObject* parent)
: QObject(parent)
{
}
void Channel::onRecvPostion(const QString f, const QString l)
{
emit sigCurrentPostion(f, l);
}
void Channel::mapToWin(const QString cityName)
{
emit sigCurrentCityName(cityName);
}
void Channel::currentCityName(QString& cityName)
{
cityName = m_currentCityName;
}
根据地理位置进行网络请求,获取地里位置经纬度
#pragma once
#include <qobject.h>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
class AddressToPosition : public QObject
{
Q_OBJECT
public:
explicit AddressToPosition(QObject* parent = nullptr);
void locatCoord(std::tuple<double, double>& data);
void setCurrentCityName(const QString cityName);
public slots:
void onAddressRequest(const QString);
void onRequestRe();
void onError(QNetworkReply::NetworkError);
private:
QString m_Key;
QNetworkReply* m_pReply;
std::tuple<double, double> m_tupeResult;
QString m_currentCityName;
};
#include "AddressToPosition.h"
#include <QUrlQuery>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>
#include <QEventLoop>
#include <QTimer>
#pragma comment(lib,"Qt5Networkd.lib")
AddressToPosition::AddressToPosition(QObject* parent)
: QObject(parent)
, m_Key("您自己的密钥")
{
}
void AddressToPosition::setCurrentCityName(const QString cityName)
{
m_currentCityName = cityName;
}
void AddressToPosition::onAddressRequest(const QString locat)
{
const QString apiUrl = QString("http://api.map.baidu.com/geocoder?");
QUrl url(apiUrl);
QUrlQuery urlQuery;
urlQuery.addQueryItem("address", m_currentCityName + locat);
urlQuery.addQueryItem("output", "json");
urlQuery.addQueryItem("key", m_Key);
url.setQuery(urlQuery);
QEventLoop eventLoop;
QNetworkAccessManager networkAcManager;
QNetworkRequest networkRequest(url);
m_pReply = networkAcManager.get(networkRequest);
connect(m_pReply, &QNetworkReply::finished, this, &AddressToPosition::onRequestRe);
connect(&networkAcManager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
connect(m_pReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
eventLoop.exec();
}
void AddressToPosition::onError(QNetworkReply::NetworkError error)
{
if (error != QNetworkReply::NoError)
{
QMessageBox::information(nullptr, QStringLiteral("提示"), QStringLiteral("网络请求失败!"));
}
}
void AddressToPosition::onRequestRe()
{
auto workReply = dynamic_cast<QNetworkReply*>(sender());
if (!workReply)return;
auto error = workReply->error();
if (workReply->error() != QNetworkReply::NoError)
{
QMessageBox::information(nullptr, QStringLiteral("提示"), QStringLiteral("请求失败!"));
return;
}
QByteArray array = workReply->readAll();
auto data = array.data();
QJsonDocument jsonDocument = QJsonDocument::fromJson(array);
QJsonObject obj = jsonDocument.object();
QString status = obj.value("status").toString();
if (status != "OK")
{
QMessageBox::information(nullptr, QStringLiteral("提示"), QStringLiteral("数据有误!"));
return;
}
QJsonObject location = obj["result"].toObject();
QJsonObject loca = location["location"].toObject();
double lng = loca["lng"].toDouble();
double lat = loca["lat"].toDouble();
m_tupeResult = std::make_tuple(lng, lat);
}
void AddressToPosition::locatCoord(std::tuple<double, double>& info)
{
info = m_tupeResult;
}