vs2013、qt5.5.1、qwebview通过leaflet开源地图Javascript库加载多种地图,简单交互

首先,地图建议选用高德和google。
百度的加载比较复杂,坐标处理很麻烦,浪费我不少时间。
网上原始的例子用的是arcgis之类的地图,访问速度不稳定,有时候卡很久才显示。
与cpp程序的交互,主要是显示指定点,设置点的名称,图标。如果需要其它复杂功能,可以查leaflet的帮助文档(官网有例子)。

先上html代码,文件名leaflet_test.html

<!DOCTYPE html>
<html>
<head>

    <title>Layers Control Tutorial - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
    
    <style>
        html, body {
			width: 100%;
            height: 100%;
            margin: 0;
        }
        #map {
            width: 100%;
            height: 100%;
            min-height: 100%;
            overflow: hidden;
            margin: 0;
            position: absolute;
        }
    </style>


</head>
<body>

<div id='map'></div>

<script>
    //地图marker数组
    var markers=[];
    var markers2=[];
    var markers3=[];

    var marker1 =L.marker([30.532664, 114.437911]).bindPopup('东湖绿道');

    markers.push(marker1);

    //利用marker数组构建marker图层
    var citiesLayer = L.layerGroup(markers);
    var citiesLayer2 = L.layerGroup(markers2);
    var citiesLayer3 = L.layerGroup(markers3);

    //利用切片地图服务地址,创建图层
    var grayscaleLayer= L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}',
        {id: 'map11'});
    var streetsLayer  = L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
        {id: 'map12'});
    
    var googleLayer  = L.tileLayer('http://{s}.google.cn/vt/lyrs=s&hl=zh-CN&gl=CN&src=app&y={y}&x={x}&z={z}&s=Ga', {
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
    });
    var gaodeLayer = L.tileLayer("http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",{
                    attribution: '&copy; 高德地图',
                    subdomains: "1234"
                });
    
    //1、基础地图
    var baseLayers = {
        "高德道路": gaodeLayer,
        "Google卫星": googleLayer,
        "ArcGIS道路": grayscaleLayer,
        "ArcGIS道路(夜景)": streetsLayer,
    };

    //1、业务图层
    var overLayers = {
        "传感器": citiesLayer,
        "监测信息": citiesLayer2,
        "其它图层": citiesLayer3,
    };

    var map = L.map('map', {
        minZoom: 3,
        maxZoom: 16,
        center: [30.532664, 114.437911],
        zoom: 13,
        layers: [gaodeLayer, citiesLayer],//默认显示的图层
        //zoomDelta: 0.5,//点击+-按钮的放缩刻度尺度,默认值1
        //zoomSnap: 0.5,//地图能放缩的zoom的最小刻度尺度,默认值1
        fullscreenControl: true,//全屏控件,不显示
        zoomControl: true,//放大缩小控件,不显示
        attributionControl: false//右下角属性控件,不显示
    });

    //map的图层控件
    var layerControl=L.control.layers(baseLayers, overLayers);
    map.addControl(layerControl);


    //单个图层,也可以通过,map,addLayer()来添加


    //map.setView([36.045, 103.83333], 15);//切换地图视野范围
    //和setView类似,但是flyTo会带一个平滑的动画
    //map.flyTo([36.045, 103.83333], 15,{ animate: true, duration: 0.2 });
    //map.setZoom(0);
    map.locate({//定位到当前位置。可能只对移动端有效。
	  setView: true,
	  maxZoom: 16
	});
	map.on('locationfound', function(e) {//定位处理函数
	  var radius = e.accuracy / 2;
	  L.marker(e.latlng).addTo(m).bindPopup("你就在这个圈内");
	  L.circle(e.latlng, radius).addTo(m);
	});
	map.on('locationerror', function(e) {//
	  console.log('定位出错=====>', e);
	});
	
	var mypop = L.popup();//弹出对话框
	map.on('click', function(e) {
	  var content = '当前点坐标:<br>';
	  content += e.latlng.toString();
	  mypop.setLatLng(e.latlng)
       .setContent(content)
       .openOn(map);
	});
	
	var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: 'leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
	});

function doLocal(longitude, latitude)  //给qt调用的接口
{
	var marker_temp =L.marker([latitude, longitude]).bindPopup('item name.').addTo(citiesLayer);
	markers.push(marker_temp);
	map.flyTo([latitude, longitude], 15,{ animate: true, duration: 0.2 });
}
function doLocal_name(longitude, latitude, item_name)  //给qt调用的接口
{
	var marker_temp =L.marker([latitude, longitude]).bindPopup(item_name).addTo(citiesLayer);
	markers.push(marker_temp);
	map.flyTo([latitude, longitude], 15,{ animate: true, duration: 0.2 });
	
	//marker_temp.on('click', function(e) {//有效。监听任意对象的点击事件。
	//  console.log(e);
	//  alert('当前点被点击。');
	//})
}
function doLocal_name_icon(longitude, latitude, item_name,icon_file)  //给qt调用的接口
{
	var icon_temp = new LeafIcon({iconUrl: icon_file});
	var marker_temp =L.marker([latitude, longitude], {icon: icon_temp}).bindPopup(item_name).addTo(citiesLayer);
	markers.push(marker_temp);
	map.flyTo([latitude, longitude], 15,{ animate: true, duration: 0.2 });
}
</script>
</body>
</html>

qwebview加载地图页面的代码


	m_pWebView = new QWebView(this);
	//
	QGridLayout *gridLayout = new QGridLayout(this);
	gridLayout->setSpacing(6);
	gridLayout->setContentsMargins(11, 11, 11, 11);
	gridLayout->setObjectName(QStringLiteral("gridLayout"));
	gridLayout->addWidget(m_pWebView, 0, 0, 1, 1);

	m_pWebView->showMaximized();
	connect(m_pWebView, SIGNAL(loadFinished(bool)), this, SLOT(onPageLoadFinished(bool)));
	//
	m_pWebView->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
	m_pWebView->settings()->setAttribute(QWebSettings::JavaEnabled, true);
	m_pWebView->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
	m_pWebView->settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard, true);
	m_pWebView->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
	m_pWebView->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
	m_pWebView->settings()->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true);
	m_pWebView->settings()->setAttribute(QWebSettings::JavascriptCanCloseWindows, true);
	m_pWebView->settings()->setAttribute(QWebSettings::AutoLoadImages, true);
	m_pWebView->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
	//
	m_pWebView->settings()->setAttribute(QWebSettings::CSSGridLayoutEnabled, true);

	m_pWebView->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);//缓存
	m_pWebView->settings()->enablePersistentStorage(QDir::homePath());//缓存目录




		QString file_name = QString((yf::global_data::get_config_folder() + "/").c_str()) + strCurMapUrl_;
		//
		QFileInfo file(file_name);
		QString url = "file:///";
		url += file.absoluteFilePath();
		if (strCurMapUrl_.indexOf(".html") > 0)
		{
		}
		else
		{
			url = strCurMapUrl_;//www.163.com之类网址
		}
		//m_pWebView->setUrl(QUrl(url));
		m_pWebView->load(QUrl(url));//与setUrl似乎无区别。
		m_pWebView->show();
		m_pWebView->showMaximized();
		m_pWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);

显示图标的代码

			QString fun = QString("doLocal_name_icon(\"%1\",\"%2\",\"%3\",\"%4\");")
				.arg(lon_str_.c_str()).arg(lat_str_.c_str())
				.arg(item_name_.c_str()).arg(icon_name_.c_str());
			m_pWebView->page()->mainFrame()->evaluateJavaScript(fun);
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值