赞
踩
以下是在线高德地图地址。
http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8
以下是代码示例:
- #include <QApplication>
- #include <QMainWindow>
- #include "qgisinterface.h"
- #include "qgsproviderregistry.h"
- #include "qgsrasterlayer.h"
- #include "qgsproject.h"
- #include "qgsmapcanvas.h"
- int main(int argc, char *argv[])
- {
- // 初始化QGIS
- QgsApplication app(argc, argv, true);
- app.initQgis();
- // 创建主窗口
- QMainWindow mainWindow;
- mainWindow.setWindowTitle("QGIS with Amap");
- // 创建地图Canvas
- QgsMapCanvas* mapCanvas = new QgsMapCanvas(&mainWindow);
- mapCanvas->setCanvasColor(Qt::white);
- mapCanvas->setVisible(true);
- mapCanvas->setFrameStyle(0);
- mainWindow.setCentralWidget(mapCanvas);
- // 创建栅格图层
- QgsRasterLayer* amapLayer = new QgsRasterLayer("http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8", "Amap", "wms");
- if (amapLayer->isValid())
- {
- QgsProject::instance()->addMapLayer(amapLayer);
- QgsRectangle extent = amapLayer->extent();
- mapCanvas->setExtent(extent);
- }
- else
- {
- QMessageBox::critical(&mainWindow, "Error", "Could not load Amap layer.");
- return -1;
- }
- // 设置地图范围和投影
- QgsCoordinateReferenceSystem crs("EPSG:3857");
- mapCanvas->setDestinationCrs(crs);
- mapCanvas->enableAntiAliasing(true);
- // 显示主窗口
- mainWindow.show();
- // 执行QGIS事件循环
- return app.exec();
- }
结果运行结果无效并报错:
Raster layer Cannot instantiate the 'wms' data provider
大概的意思就是说不能初始化wms的东西,就是wms的相关驱动没有加载好。
解决办法:
1.设置路径
- //设置前缀路径
- QgsApplication app(argc, argv, true);
- app.setPrefixPath("E:/OSGeo4W/apps/qgis-ltr-dev", true);
- app.initQgis();
2.将驱动文件拷贝到运行目录下
不需要设置setPrefixPath()。
将E:/OSGeo4W/apps/qgis-ltr-dev/plugins目录拷贝到生成程序的运行目录下,因为程序启动起来加载的是本地的plugins下的插件。
注意不要拷贝错了,我下载的目录下有两个qgis目录,你使用的哪个路径下的库来编译的程序,就拷贝哪个路径下的plugins目录,否则有可能导致程序起不来。
提供一个编码url的类
- #ifndef QGSXYZCONNECTION_H
- #define QGSXYZCONNECTION_H
-
- #include <QStringList>
-
- struct QgsXyzConnection
- {
- QString name;
- QString url;
- int zMin = -1;
- int zMax = -1;
- // Authentication configuration id
- QString authCfg;
- // HTTP Basic username
- QString username;
- // HTTP Basic password
- QString password;
- // Referer
- QString referer;
- // tile pixel ratio (0 = unknown (not scaled), 1.0 = 256x256, 2.0 = 512x512)
- double tilePixelRatio = 0;
- bool hidden = false;
-
- QString encodedUri() const;
- };
-
- //! Utility class for handling list of connections to XYZ tile layers
- class QgsXyzConnectionUtils
- {
- public:
- //! Returns list of existing connections, unless the hidden ones
- static QStringList connectionList();
-
- //! Returns last used connection
- static QString selectedConnection();
-
- //! Saves name of the last used connection
- static void setSelectedConnection( const QString &connName );
-
- //! Returns connection details
- static QgsXyzConnection connection( const QString &name );
-
- //! Removes a connection from the list
- static void deleteConnection( const QString &name );
-
- //! Adds a new connection to the list
- static void addConnection( const QgsXyzConnection &conn );
- };
-
-
- #endif // QGSXYZCONNECTION_H
-
-
-
- #include <qgslogger.h>
- #include "qgsxyzconnection.h"
-
- #include <qgsdatasourceuri.h>
- #include <qgssettings.h>
-
- QString QgsXyzConnection::encodedUri() const
- {
- QgsDataSourceUri uri;
- uri.setParam( QStringLiteral( "type" ), QStringLiteral( "xyz" ) );
- uri.setParam( QStringLiteral( "url" ), url );
- if ( zMin != -1 )
- uri.setParam( QStringLiteral( "zmin" ), QString::number( zMin ) );
- if ( zMax != -1 )
- uri.setParam( QStringLiteral( "zmax" ), QString::number( zMax ) );
- if ( ! authCfg.isEmpty() )
- uri.setAuthConfigId( authCfg );
- if ( ! username.isEmpty() )
- uri.setUsername( username );
- if ( ! password.isEmpty() )
- uri.setPassword( password );
- if ( ! referer.isEmpty() )
- uri.setParam( QStringLiteral( "referer" ), referer );
- if ( tilePixelRatio != 0 )
- uri.setParam( QStringLiteral( "tilePixelRatio" ), QString::number( tilePixelRatio ) );
- return uri.encodedUri();
- }
-
- QStringList QgsXyzConnectionUtils::connectionList()
- {
- QgsSettings settings;
- QStringList connList;
-
- settings.beginGroup( QStringLiteral( "qgis/connections-xyz" ) );
- connList = settings.childGroups();
-
- const QStringList global = settings.globalChildGroups();
- settings.endGroup();
-
- for ( const auto &s : global )
- {
- settings.beginGroup( "qgis/connections-xyz/" + s );
- bool isHidden = settings.value( QStringLiteral( "hidden" ), false ).toBool();
- settings.endGroup();
- if ( isHidden )
- {
- connList.removeOne( s );
- }
- }
-
- return connList;
- }
-
- QString QgsXyzConnectionUtils::selectedConnection()
- {
- QgsSettings settings;
- return settings.value( QStringLiteral( "qgis/connections-xyz/selected" ) ).toString();
- }
-
- void QgsXyzConnectionUtils::setSelectedConnection( const QString &name )
- {
- QgsSettings settings;
- return settings.setValue( QStringLiteral( "qgis/connections-xyz/selected" ), name );
- }
-
- QgsXyzConnection QgsXyzConnectionUtils::connection( const QString &name )
- {
- QgsSettings settings;
- settings.beginGroup( "qgis/connections-xyz/" + name );
-
- QgsXyzConnection conn;
- conn.name = name;
- conn.url = settings.value( QStringLiteral( "url" ) ).toString();
- conn.zMin = settings.value( QStringLiteral( "zmin" ), -1 ).toInt();
- conn.zMax = settings.value( QStringLiteral( "zmax" ), -1 ).toInt();
- conn.authCfg = settings.value( QStringLiteral( "authcfg" ) ).toString();
- conn.username = settings.value( QStringLiteral( "username" ) ).toString();
- conn.password = settings.value( QStringLiteral( "password" ) ).toString();
- conn.referer = settings.value( QStringLiteral( "referer" ) ).toString();
- conn.tilePixelRatio = settings.value( QStringLiteral( "tilePixelRatio" ), 0 ).toDouble();
- conn.hidden = settings.value( QStringLiteral( "hidden" ) ).toBool();
- return conn;
- }
-
- void QgsXyzConnectionUtils::deleteConnection( const QString &name )
- {
- QgsSettings settings;
- settings.remove( "qgis/connections-xyz/" + name );
-
- settings.beginGroup( QStringLiteral( "qgis/connections-xyz" ) );
- QStringList global = settings.globalChildGroups();
-
- if ( global.contains( name ) )
- {
- QgsSettings settings;
- settings.beginGroup( "qgis/connections-xyz/" + name );
- settings.setValue( QStringLiteral( "hidden" ), true );
- }
-
- }
-
- void QgsXyzConnectionUtils::addConnection( const QgsXyzConnection &conn )
- {
- QgsSettings settings;
- bool addHiddenProperty = false;
-
- settings.beginGroup( QStringLiteral( "qgis/connections-xyz" ) );
- QStringList global = settings.globalChildGroups();
- if ( global.contains( conn.name ) )
- {
- addHiddenProperty = true;
- }
- settings.endGroup();
-
- settings.beginGroup( "qgis/connections-xyz/" + conn.name );
- settings.setValue( QStringLiteral( "url" ), conn.url );
- settings.setValue( QStringLiteral( "zmin" ), conn.zMin );
- settings.setValue( QStringLiteral( "zmax" ), conn.zMax );
- settings.setValue( QStringLiteral( "authcfg" ), conn.authCfg );
- settings.setValue( QStringLiteral( "username" ), conn.username );
- settings.setValue( QStringLiteral( "password" ), conn.password );
- settings.setValue( QStringLiteral( "referer" ), conn.referer );
- settings.setValue( QStringLiteral( "tilePixelRatio" ), conn.tilePixelRatio );
- if ( addHiddenProperty )
- {
- settings.setValue( QStringLiteral( "hidden" ), false );
- }
- }
-
使用:
- QgsXyzConnection xyz;
- xyz.url = QStringLiteral("http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8");
- xyz.zMin = 0;
- xyz.zMax = 18;
- xyz.tilePixelRatio = 1.0;
-
- QgsXyzConnectionUtils::addConnection(xyz);
-
- QString url2 = xyz.encodedUri();
- qDebug() << "url2 = " << url2;
-
- QgsRasterLayer *layer = addRasterLayerPrivate(url2, QStringLiteral("ocr0"), QStringLiteral("wms"));
看了评论有一些同学加载失败,以下是我整理的一个完整例子,加载失败最大的原因,我认为就是Qgis的相关运行库、驱动库没有拷贝完整。我把运行路径也截图了,可以照着参考。
加载高德地图成功效果图
自定义WQgsMapCanvas类
- #pragma once
- #include <qgsmapcanvas.h>
- #include <qgsrasterlayer.h>
- #include <QMouseEvent>
- #include <QPaintEvent>
- #include <qgspoint.h>
- #include <qgsmaptoolpan.h>
- #include <qgsrubberband.h>
- #include <qgsgeometry.h>
- #include <QDebug>
- #include <QList>
- #include <QWheelEvent>
-
-
- class WQgsMapCanvas : public QgsMapCanvas
- {
- Q_OBJECT
- public:
- WQgsMapCanvas(const QString &url,QWidget *parent = nullptr);
- ~WQgsMapCanvas();
-
- private:
- QgsRasterLayer *addRasterLayer(const QString &rasterFile, const QString &baseName);
- QgsRasterLayer *addRasterLayerPrivate(const QString &uri, const QString &name, const QString &providerKey);
-
- public:
- bool isExistRect = false;
- QRectF qRectf;
-
- protected:
- //void wheelEvent(QWheelEvent*event);
-
- private:
- QgsRasterLayer *m_layer = nullptr; //图层
-
- };
-
-
-
- #include "WQgsMapCanvas.h"
- #include <qgsmapcanvas.h>
- #include <qgsmaptoolidentify.h>
- #include <qgsmaptool.h>
- #include <qgssymbollayer.h>
- #include <qgsannotationmarkeritem.h>
- #include <qgsannotationlayer.h>
- #include <qgsmarkersymbollayer.h>
- #include <qgssinglesymbolrenderer.h>
- #include <qgsrubberband.h>
- #include <qgsannotationpointtextitem.h>
- #include <qgsmapcanvasannotationitem.h>
- #include <qgstextannotation.h>
- #include <QTextDocument>
- #include "QgsMapToolSelectItem.h"
- #include <QRegularExpression>
- #include "qgsxyzconnection.h"
- #include <qglobal.h>
-
- QgsRasterLayer *WQgsMapCanvas::addRasterLayer(const QString &rasterFile, const QString &baseName)
- {
- return addRasterLayerPrivate(rasterFile, baseName, QString());
- }
-
- QgsRasterLayer *WQgsMapCanvas::addRasterLayerPrivate(const QString &uri, const QString &name, const QString &providerKey)
- {
- QString shortName = name;
- QRegularExpression reRasterFile(QStringLiteral("^/vsi(.+/)*([^ ]+)( .+)?$"), QRegularExpression::CaseInsensitiveOption);
- QRegularExpressionMatch matchRasterFile = reRasterFile.match(name);
-
- if (matchRasterFile.hasMatch())
- {
- if (!matchRasterFile.captured(2).isEmpty())
- {
- shortName = matchRasterFile.captured(2);
- }
- }
-
- QgsSettings settings;
- QString baseName = settings.value(QStringLiteral("qgis/formatLayerName"), false).toBool() ? QgsMapLayer::formatLayerName(shortName) : shortName;
-
- //QgsDebugMsgLevel("Creating new raster layer using " + uri
- // + " with baseName of " + baseName, 2);
-
- QgsRasterLayer *layer = nullptr;
- // XXX ya know QgsRasterLayer can snip out the basename on its own;
- // XXX why do we have to pass it in for it?
- // ET : we may not be getting "normal" files here, so we still need the baseName argument
- if (!providerKey.isEmpty() && uri.endsWith(QLatin1String(".adf"), Qt::CaseInsensitive))
- {
- QFileInfo fileInfo(uri);
- QString dirName = fileInfo.path();
- layer = new QgsRasterLayer(dirName, QFileInfo(dirName).completeBaseName(), QStringLiteral("gdal"));
- }
- else if (providerKey.isEmpty())
- layer = new QgsRasterLayer(uri, baseName); // fi.completeBaseName());
- else
- layer = new QgsRasterLayer(uri, baseName, providerKey);
-
-
- QString title;
- bool ok = false;
-
- if (!layer->isValid())
- {
- QgsError error = layer->error();
- title = "Invalid Layer";
- qDebug() << error.message(QgsErrorMessage::Text);
- }
-
- if (layer)
- layer->loadDefaultMetadata(ok);
-
-
- return layer;
- }
-
-
- QList<QgsMapLayer *> g_layers;
- QList<QgsMapLayer *> g_tempLayer;
- bool g_is3857crs = false;
-
- WQgsMapCanvas::WQgsMapCanvas(const QString &url,QWidget *parent /*= nullptr*/)
- : QgsMapCanvas(parent)
- {
- setCanvasColor(QColor(255, 255, 255));
-
- QgsRasterLayer *layer = nullptr;
-
- if (url.contains("http"))
- {
- QgsXyzConnection xyz;
- xyz.url = url;
- xyz.zMin = 0;
- xyz.zMax = 18;
- xyz.tilePixelRatio = 1.0;
-
- QgsXyzConnectionUtils::addConnection(xyz);
-
- QString url2 = xyz.encodedUri();
- layer = addRasterLayerPrivate(url2, "OSM", "wms");
- if (!layer->isValid())
- {
- QgsError error = layer->error();
- qDebug() << error.message(QgsErrorMessage::Text);
- }
- }
- else
- {
- layer = new QgsRasterLayer(url); // fi.completeBaseName());
- }
-
- if (!layer->isValid())
- {
- QgsError error = layer->error();
- qDebug() << error.message(QgsErrorMessage::Text);
- }
-
- QgsCoordinateReferenceSystem crs = layer->crs();
- if (crs.authid().contains("3857"))
- {
- g_is3857crs = true;
- }
- qDebug() << "crs = " << crs.authid();
- this->setDestinationCrs(crs);
- g_layers.append(layer);
- g_tempLayer.append(layer);
-
- setExtent(layer->extent());
- enableAntiAliasing(true);
- setLayers(g_layers);
- this->zoomToFullExtent();
- refresh();
- }
-
- WQgsMapCanvas::~WQgsMapCanvas()
- {
-
- }
调用:
- m_canvas = new WQgsMapCanvas("http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8");
-
- setCentralWidget(m_canvas);
运行路径截图
剩下的就是qgis运行的动态库了
查看完整的配置: 目录3
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。