QT笔记:Qt5.14.2加载并显示百度在线地图
阅读原文时间:2021年04月23日阅读:1

1、创建百度地图应用

进入百度地图开放平台,注册并登录,在控制台里创建应用。
![](https://article.cdnof.com/2104/7e7e9517-6abd-40be-a62f-57aac26de9f4.png)

2、创建百度地图HTML

内容如下:

<!doctype html>
<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>百度地图</title>
    <style type="text/css">
    body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
            p{margin-left:5px; font-size:14px;}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=你申请的AK"></script>
</head>
    <body>
    <div id="allmap" style="overflow:hidden;zoom:1;position:relative;">    
        <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;"></div>
    </div>
    <script type="text/javascript">

    // 百度地图API功能
    //地图初始化
    var map = new BMap.Map("allmap");
    map.centerAndZoom(new BMap.Point(104.166, 30.700), 19);
    var navigationControl = new BMap.NavigationControl({
      anchor: BMAP_ANCHOR_TOP_LEFT,
      type: BMAP_NAVIGATION_CONTROL_LARGE,
      enableGeolocation: true
      });
    map.addControl(navigationControl);            // 添加平移缩放控件
    map.addControl(new BMap.ScaleControl());      // 添加比例尺控件
    var overviewControl = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:true});
    map.addControl(overviewControl);              // 添加缩略图控件控件
    var mapType1 = new BMap.MapTypeControl({anchor: BMAP_ANCHOR_TOP_RIGHT,mapTypes:[BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]});
    map.addControl(mapType1);                     // 添加地图类型控件
    map.enableScrollWheelZoom();   //启用滚轮放大缩小,默认禁用
    map.enableContinuousZoom();    //启用地图惯性拖拽,默认禁用
    map.enableKeyboard();          //启用键盘移动地图
    map.enableDragging();          //启用地图拖拽
    map.enableDoubleClickZoom();   //启用双击放大
    //添加鼠标点击事件,显示当前点的经纬度
    map.addEventListener("click",function(e){
        alert(e.point.lng + " , " + e.point.lat);
    }); 
</script>
</body>
</html>

3、Qt使用QWebEngineView显示

void Widget::on_loadMap_clicked()
{
    QString htmlPath = "E:/code/QT/MyMapView/MyMapView.html";
    QUrl testUrl("E:/code/QT/MyMapView/");
    QFile file(htmlPath);
    if (!file.open(QIODevice::ReadOnly))
    {
        return;
    }
    QString htmlData = file.readAll().constData();
    file.close();
    ui->mapView->setHtml(htmlData,testUrl);
}

效果展示