一、环境配置
1. 项目依赖
// .pro文件配置
QT += webenginewidgets webchannel
LIBS += -lQt5WebEngineCore -lQt5WebChannel
2. 百度地图API配置
<!-- map.html -->
<script src="http://api.map.baidu.com/api?type=webgl&v=3.0&ak=YOUR_API_KEY"></script>
<script src="qwebchannel.js"></script>
二、核心代码实现
1. Qt端界面设计
// mainwindow.h
class MainWindow : public QMainWindow {Q_OBJECT
public:MainWindow(QWidget *parent = nullptr);private slots:void onPlanRoute();void handleRouteResult(const QString &points);private:QWebEngineView *m_webView;QWebChannel *m_channel;
};
2. 地图初始化
// mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {m_webView = new QWebEngineView(this);m_channel = new QWebChannel(this);// 设置通信对象m_channel->registerObject("mapBridge", this);m_webView->page()->setWebChannel(m_channel);// 加载地图页面m_webView->setUrl(QUrl("qrc:/map/map.html"));setCentralWidget(m_webView);
}// 地图控件初始化
void initMap() {QString js = R"(var map = new BMapGL.Map("container");map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 14);map.enableScrollWheelZoom(true);// 注册Qt回调new QWebChannel(qt.webChannelTransport, function(channel) {window.qtBridge = channel.objects.mapBridge;});)";m_webView->page()->runJavaScript(js);
}
3. 路径规划实现
// 路径规划请求
void MainWindow::onPlanRoute() {QString startLng = ui->startLng->text();QString startLat = ui->startLat->text();QString endLng = ui->endLng->text();QString endLat = ui->endLat->text();QString js = QString(R"(var driving = new BMapGL.DrivingRoute(map, {renderOptions: { map: map, autoViewport: true }});driving.search(new BMapGL.Point(%1, %2), new BMapGL.Point(%3, %4));driving.setSearchCompleteCallback(function(results) {if (driving.getStatus() == BMAP_STATUS_SUCCESS) {var points = [];var route = results.getPlan(0).getRoute(0);for(var i=0; i<route.getNumSteps(); i++) {points.push(route.getStep(i).getPath());}qtBridge.handleRouteResult(JSON.stringify(points));}});)").arg(startLng).arg(startLat).arg(endLng).arg(endLat);m_webView->page()->runJavaScript(js);
}// 处理路径结果
void MainWindow::handleRouteResult(const QString &points) {QJsonDocument doc = QJsonDocument::fromJson(points.toUtf8());QJsonArray pathPoints = doc.array();QPainterPath path;for(auto point : pathPoints) {QPointF p = point.toObject()["lng"].toDouble(), point.toObject()["lat"].toDouble());path.lineTo(p);}// 在地图上绘制路径QString drawJs = QString("addPolyline(%1)").arg(path.toString());m_webView->page()->runJavaScript(drawJs);
}
三、JavaScript交互层
1. 路径绘制函数
// map.html
function addPolyline(points) {var path = [];points.forEach(function(p) {path.push(new BMapGL.Point(p.lng, p.lat));});var polyline = new BMapGL.Polyline(path, {strokeColor: "#FF0000",strokeWeight: 5,strokeOpacity: 0.8});map.addOverlay(polyline);
}
2. 坐标转换接口
// 实现WGS84转BD09坐标
function convertCoords(lng, lat) {var point = new BMapGL.Point(lng, lat);return BMapGL.convertor.translate(point, 1);
}
四、界面布局示例
<!-- mainwindow.ui -->
<widget class="QMainWindow" name="MainWindow"><layout class="QGridLayout"><item row="0" column="0"><QLineEdit placeholderText="起点经度"/></item><item row="0" column="1"><QLineEdit placeholderText="起点纬度"/></item><item row="1" column="0"><QLineEdit placeholderText="终点经度"/></item><item row="1" column="1"><QLineEdit placeholderText="终点纬度"/></item><item row="2" column="0" colspan="2"><QPushButton text="规划路径" clicked="onPlanRoute"/></item></layout>
</widget>
五、关键调试技巧
-
坐标验证:
console.log("起点坐标:", new BMapGL.Point(116.404, 39.915));
-
路径可视化调试:
map.addOverlay(new BMapGL.Marker(new BMapGL.Point(116.404, 39.915)));
-
网络请求监控:
connect(m_webView->page(), &QWebEnginePage::networkRequestFinished,[](QNetworkReply* reply){qDebug() << "请求状态:" << reply->url() << reply->error();});
六、扩展功能实现
1. 实时路径更新
// 定时刷新路径
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [=]{m_webView->page()->runJavaScript("updatePath()");
});
timer->start(1000);
2. 路径优化算法
// 道路平滑处理
QString smoothJs = R"(var points = [];for(var i=0; i<path.length-1; i++) {var p1 = path[i], p2=path[i+1];for(var t=0; t<=10; t++) {var x = p1.lng + (p2.lng-p1.lng)*t/10;var y = p1.lat + (p2.lat-p1.lat)*t/10;points.push(new BMapGL.Point(x, y));}}return points;
)";
参考代码 基于QT的百度地图开发。实现简单的路径规划功能 www.youwenfan.com/contentcnj/69896.html
七、完整工程结构
MapApp/
├── Src/
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mapengine.cpp
├── Res/
│ ├── html/
│ │ ├── map.html
│ │ └── qwebchannel.js
│ └── styles/
├── CMakeLists.txt
└── .pro