This is a static archive of our old OpenStreetMap Help Site. Please post any new questions and answers at community.osm.org.

Load OSM tiles using URL in custom QGIS application (C++)

0

I am trying to write a C++ version of a custom QGIS (v 3.10) application I initially wrote in Python that overlays data onto OpenStreetMap. I am able to do this successfully by loading online tiles via URL as a raster layer in Python using WMS provider; however the same URL does not work when using the C++ API, despite being able to load other raster files (e.g. GeoTIFF).

Code in Python:

url = 'type=xyz&url=https://a.tile.openstreetmap.org'
url += '/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
prj = QgsProject()
qmc = QgsMapCanvas()
layers = []
ras = QgsRasterLayer(url,'OpenStreetMap','wms')

if ras.isValid():
    print("Basemap loaded successfully!")
    prj.instance().addMapLayer(ras)
    qmc.setExtent(ras.extent())
    layers.append(ras)
    qmc.setLayers(layers)

 else:
     print("Unable to load basemap.")

C++ version:

QString url = "type=xyz&url=https://a.tile.openstreetmap.org";
url.append("/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857");
QgsProject() *prj = new QgsProject();
QgsMapCanvas *qmc = new QgsMapCanvas();
QList <QgsMapLayer *> layers;
QgsRasterLayer *ras = new QgsRasterLayer(url,'OpenStreetMap','wms');

if ( ras.isValid() )
{
    qDebug() << "Basemap loaded successfully!";
    prj->instance()->addMapLayer(ras);
    qmc->setExtent(ras->extent());
    layers.append(ras);
    qmc->setLayers(layers);
 } else
{
     qDebug() << "Unable to load basemap.";
 }

(Note: the layer list takes QgsMapLayer pointers in C++ but couldn't escape the vectors using &lt/&gt). I get the successful message and loaded map in Python and the invalid message and no map in C++. I have tried using other URL's but nothing has worked thus far. If there are plugins available that might help, but I would still need to write workable code without the use of the QGIS gui itself (as in most examples using plugins).

asked 06 Apr '21, 15:45

raisehellpraisedale's gravatar image

raisehellpra...
11112
accept rate: 0%

Source code available on GitHub .