C
Qt Quick Ultralite 地图示例
演示如何使用Map 控件在Qt Quick Ultralite中显示地图。
概述
本示例演示了如何使用Map 控件在Qt Quick Ultralite应用程序中显示地图。
精简地图模式
在此模式下,本示例为四个缩放级别(从 0 到 3)提供了地图图块。要放大,请选择“
”按钮;要缩小,请选择“
”按钮。在任何缩放级别下,要顺时针旋转地图,请选择“
”按钮;要逆时针旋转地图,请选择“
”按钮。 您还可以通过拖动地图来平移视图。

用户位置演示模式
演示模式模拟用户当前位置在地图上沿预定义路线的变化。要启动演示模式,请点击“
”按钮。演示模式下,除“
”和“
”按钮外,所有其他按钮均被隐藏。

演示开始时,地图会自动放大至第17级。代表用户当前位置的“
”图标以及代表兴趣点的“
”图标将显示在地图上。 要暂停演示,请点击
按钮,该按钮将变为
按钮。演示暂停期间,您可以通过拖动地图进行平移。要恢复演示,请点击
。要停止演示并返回简约地图模式,请点击
按钮。
该示例实现了Qul::MapTileFetcher 方法,用于从文件系统中获取地图图块。文件系统实现来自“fileloading”示例。地图图块采用JPEG 格式,需要使用JPEG 解码器。JPEG解码器的实现来自“imagedecoder”示例。有关更多信息,请参阅“获取地图图块”。
该示例实现了Qul::GeoPositionSource ,用于从一个虚拟位置源获取位置信息。有关详细信息,请参阅“检索位置信息”。
目标平台
在桌面端运行示例
该示例采用了imagedecoder示例中的JPEG解码器实现,该实现使用Qt来解码图像。因此,该项目需要开发版Qt来构建,以便提供头文件。
cmake examples/map -DCMAKE_PREFIX_PATH=$HOME/Qt/6.2.4/gcc_64 -DQUL_PLATFORM=Qt -DQul_ROOT=${QUL_ROOT}cmake examples\map -DCMAKE_PREFIX_PATH=C:\Qt\6.2.4\msvc2022_64 -DQUL_COMPILER_NAME=msvc -DQUL_PLATFORM=Qt -DQul_ROOT=%QUL_ROOT%
为避免与平台后端链接的 Qt 版本出现兼容性问题,两者必须使用相同版本。对于自定义构建的平台,请使用与构建桌面平台后端时相同的 Qt 版本。对于预构建的平台库,必须使用 Qt 6.2.4。
注意: 使用 MinGW时, 请将编译器名称设置为gnu ,并将路径CMAKE_PREFIX_PATH 设置为 C:\Qt\6.2.4\mingw_64。
注意:在 Linux系统上 ,Qt 依赖于 OpenGL。如果在配置示例时遇到关于缺少 OpenGL 的错误,可以使用以下命令进行安装
sudo apt install libgl1-mesa-dev
在设备上运行示例
要在目标平台上运行示例,您需要一张已格式化为FAT32 格式的SD 卡。将示例目录下offline_tiles_provider/ 中的tiles/ 目录复制到您的SD 卡的根目录中。
硬件要求
支持图像加速解码和加速旋转的设备对于实现良好的性能、高帧率和流畅的用户体验至关重要。
RAM 的内存需求会根据地图大小而有所不同。 在屏幕尺寸为 800 x 480 的STM32F769i设备上,全屏地图将占用 32 KB 的heap 和stack 内存。对于相同的屏幕尺寸,需要 3840 KB 的SDRAM 内存用于缓存地图图块图像。有关更多信息,请参阅“图像缓存”。
地图图块
该示例包含五个缩放级别的全球Web Mercator投影地图图块。每个图块均为 256 x 256 像素的 JPEG 格式图像。每个缩放级别的图块数量按2^zoomlevel×2^zoomlevel 计算得出。
地图图块位于示例目录下的offline_tiles_provider/tiles/ 文件夹中。
获取地图图块(技术预览版)
该示例从离线的外部存储中获取地图图块。
OfflineTileFetcher 类
OfflineTileFetcher 类是Qul::MapTileFetcher 类的参考实现。您可以在offline_tile_provider/offlinetilefetcher.h 和offline_tile_provider/offlinetilefetcher.cpp 文件中找到该实现。
Qul::MapTileFetcher 类有一个必须实现的Qul::MapTileFetcher::getTileImage 函数。OfflineTileFetcher 类对其实现如下:
bool OfflineTileFetcher::getTileImage(const Qul::Private::TileSpec &spec, Qul::Private::TileImage &tileImage) { // user has to configure url to point to tiles images root dir. QulString url = generateTileUrl(TILES_BASE_DIR, spec); if (url.empty()) { url = PLACEHOLDER_TILE; Qul::PlatformInterface::log("warning: tile url is empty. using placeholder tile at '%s'.\n", PLACEHOLDER_TILE); } const TileCacheMap::iterator it = tileCache.find(url); if (it != tileCache.end()) { tileImage.image = it->second; return true; } if (tileCache.size() >= maxCacheSize) removeOldestImage(); Qul::SharedImage newTileImage = findImage(url.c_str()); if (!newTileImage && url != PLACEHOLDER_TILE) { #ifndef NDEBUG Qul::PlatformInterface::log("warning: could not fetch a tile with url '%s'. using placeholder tile.\n", url.c_str()); #endif newTileImage = findImage(PLACEHOLDER_TILE); if (!newTileImage) { Qul::PlatformInterface::log("error: could not fetch a placeholder tile from '%s'.\n", PLACEHOLDER_TILE); return false; } } else if (!newTileImage) { Qul::PlatformInterface::log("error: could not fetch a placeholder tile from '%s'.\n", PLACEHOLDER_TILE); return false; } tileImage.image = newTileImage; tileCache[url] = newTileImage; cacheOrder.push_back(url); return true; }
OfflineTileFetcher 类实现了成员函数generateTileUrl ,用于根据spec 参数以及示例中CMakeLists.txt 文件中定义的TILES_BASE_DIR 来生成地图瓦片的URI 。
static int printTileSpec(char *buffer, int size, const char *baseDir, const Qul::Private::TileSpec &spec) { return std::snprintf(buffer, size, "%s%u/%u/%u.jpeg", baseDir, spec.zoom, spec.x, spec.y); } OfflineTileFetcher::QulString OfflineTileFetcher::generateTileUrl(const char *baseDir, const Qul::Private::TileSpec &spec) const { const int size = printTileSpec(nullptr, 0, baseDir, spec); if (size <= 0) { Qul::PlatformInterface::log("error: failed to calculate the required buffer size for the tile url."); return QulString(); } QulString url; url.resize(size + 1); // The generated string has a length of at most n-1, leaving space for the // additional terminating null character. printTileSpec(&url[0], url.size(), baseDir, spec); url.resize(size); return url; }
OfflineTileFetcher 类使用FileCache::get 来访问、解码并将解码后的地图图块图像缓存到RAM中。FileCache::get 返回Qul::SharedImage 对象。
Qul::SharedImage OfflineTileFetcher::findImage(const char *url) { if (m_fileCache) return m_fileCache->get(url); return Qul::Private::findImageForString(url); }
OfflineTileFetcher 实现了缓存机制,用于存储已访问过的地图图块。
... tileCache[url] = newTileImage; ...
缓存已访问的地图图块会保留对Qul::SharedImage 的引用,如果能在RAM缓存中找到该图块,则返回已解码的图块图像。
... const TileCacheMap::iterator it = tileCache.find(url); if (it != tileCache.end()) { tileImage.image = it->second; return true; } ...
OfflineTileFetcher 使用在CMakeLists.txt 中定义的MAX_CACHE_SIZE 来设置maxCacheSize ,随后将最旧的缓存条目移除。
OfflineTileFetcher::OfflineTileFetcher(bool useFileCache) ... , maxCacheSize(MAX_CACHE_SIZE) {} void OfflineTileFetcher::removeOldestImage() { for (int i = 0; i < MAX_CACHE_SIZE / 5 && !cacheOrder.empty(); ++i) { const QulString oldestUrl = cacheOrder.front(); cacheOrder.pop_front(); tileCache.erase(oldestUrl); } }
检索位置信息(技术预览版)
该示例模拟了从一个虚拟位置源中检索位置信息的过程。
DummyPositionSource 类
DummyPositionSource 类是Qul::GeoPositionSource 类的参考实现。您可以在dummy_position_source/dummypositionsource.h 和dummy_position_source/dummypositionsource.cpp 文件中找到该实现。
Qul::GeoPositionSource 类有一个必须实现的Qul::GeoPositionSource::getCurrentPosition 函数。DummyPositionSource 类对其实现如下:
Qul::Private::PositionSource::SourceError DummyPositionSource::getCurrentPosition(Qul::GeoPositionInfo &positionInfo) { const size_t lastIndex = dataSource.size() - 1; IndexManager &indexManager = IndexManager::instance(); Qul::GeoPositionInfo posInfo = dataSource[indexManager.getIndex()]; positionInfo.latitude = posInfo.latitude; positionInfo.longitude = posInfo.longitude; positionInfo.direction = posInfo.direction; positionInfo.speed = posInfo.speed; positionInfo.timestamp = posInfo.timestamp; if (indexManager.getIndex() == lastIndex) return Qul::Private::PositionSource::ClosedError; indexManager.incrementIndex(); return Qul::Private::PositionSource::NoError; }
DummyPositionSource::getCurrentPosition 该函数用于从dataSource 向量中访问模拟位置数据。dataSource 向量的定义位于dummy_position_source/dummypositiondata.cpp 中。
extern const std::vector<Qul::GeoPositionInfo, Qul::PlatformInterface::Allocator<Qul::GeoPositionInfo> > dataSource = {{65.05877, 25.45545, 270, 0.000000, 1754406549865}, {65.05877, 25.455422549019605, 270, 1.287166, 1754406550864}, {65.05877, 25.455395098039215, 270, 1.287166, 1754406551866}, ... {65.0542974509804, 25.456510980392157, 248.6951536973353, 0.660902, 1754407107864}, {65.05427156862746, 25.45636862745098, 248.6951535146238, 7.269921, 1754407108858}, {65.05427078431373, 25.45636431372549, 248.6951535146238, 0.220301, 1754407109868}, {65.05427, 25.45636, 248.6951535146238, 0.220301, 1754407110869}};
为了控制从 C++ 和 QML 中访问 `dataSource ` 中的哪个位置数据条目,已在dummy_position_source/indexmanager.h 中实现了 `IndexManager ` 类。
class IndexManager : public Qul::Singleton<IndexManager> { public: IndexManager() : m_index(0){}; void setIndex(size_t i) { m_index = i; } size_t getIndex() const { return m_index; } void incrementIndex() { m_index++; } private: size_t m_index; };
DummyPositionSource::getCurrentPosition 当到达最后一个位置数据条目时,该函数返回CloseError 以停止更新当前位置。否则,当PositionSource 调用该函数时,它会返回NoError ,以根据updateInterval 属性的值继续更新当前位置。
项目结构
CMake 项目文件
CMakeLists.txt 文件包含针对桌面平台和STM32F769i平台的配置。
CMake 编译定义
TILES_BASE_DIR该路径指向地图图块所在的根目录。PLACEHOLDER_TILE该路径指向一张占位图,用于用户平移超出生成的地图区域时显示。MAX_CACHE_SIZE用于设置超过该大小时将删除旧缓存条目的阈值。
桌面配置
桌面配置依赖于文件加载示例中POSIX 文件系统实现来访问地图图块的图像,以及图像解码器示例中JPEG 桌面图像解码器实现来解码地图图块的图像。
target_sources(map PRIVATE
...
../imagedecoder/desktop/desktopimagedecoder.cpp
../fileloading/posix/posixfilesystem.cpp
)STM32F769i配置
该平台配置依赖于文件加载示例中的FATFS 文件系统实现,用于访问SD 卡中的地图图块图像;同时依赖于图像解码器示例中的硬件JPEG 图像解码器,用于解码地图图块图像。
# file system sources
target_sources(map PRIVATE
../fileloading/3rdparty/FatFs/src/diskio.c
../fileloading/3rdparty/FatFs/src/ff.c
../fileloading/3rdparty/FatFs/src/ff_gen_drv.c
../fileloading/3rdparty/FatFs/src/sd_diskio.c
../fileloading/3rdparty/FatFs/src/option/unicode.c
${QUL_BOARD_SDK_DIR}/Drivers/STM32F7xx_HAL_Driver/Src/stm32f7xx_ll_sdmmc.c
${QUL_BOARD_SDK_DIR}/Drivers/STM32F7xx_HAL_Driver/Src/stm32f7xx_hal_sd.c
${QUL_BOARD_SDK_DIR}/Drivers/BSP/STM32F769I-Discovery/stm32f769i_discovery_sd.c
)
# jpeg decoder sources
target_sources(map PRIVATE
${QUL_BOARD_SDK_DIR}/Drivers/STM32F7xx_HAL_Driver/Src/stm32f7xx_hal_jpeg.c
../imagedecoder/stm/${STM32XX}/stm32f7xx_hal_msp.c
../imagedecoder/stm/${STM32XX}/buffer_config.cpp
../imagedecoder/stm/stmimagedecoder.cpp
../imagedecoder/common/jpeg.cpp
../imagedecoder/3rdparty/stm/Utilities/JPEG/jpeg_utils.c
)QmlProject 文件
示例中的 QmlProject 文件列出了所需的 QML 文件、图像文件、接口文件以及Qt Quick Ultralite 模块。它还将MCU.Config.maxResourceCacheSize设置为在目标平台上可正常运行的值。
// Copyright (C) 2026 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial
import QmlProject
Project {
mainFile: "map.qml"
QmlFiles {
files: [
"MapButton.qml",
"MapContainer.qml",
"MapParameters.qml",
"MapMarker.qml",
"CopyrightText.qml"
]
}
ModuleFiles {
MCU.qulModules: ["Positioning", "Location"]
}
InterfaceFiles {
files: [
"dummy_position_source/indexmanager.h"
]
}
MCU.Config {
maxResourceCacheSize: 4000000
}
ImageFiles {
MCU.base: "icons/24px"
files: [
"icons/24px/plus.png",
"icons/24px/minus.png",
"icons/24px/rotate-right.png",
"icons/24px/rotate-left.png",
"icons/24px/nav-arrow.png",
"icons/24px/location-marker.png",
"icons/24px/start-resume.png",
"icons/24px/pause.png",
"icons/24px/stop.png"
]
}
}MapContainer.qml
主 QML 文件使用了Map 项,并将地图的center 设置为芬兰的奥卢市。它将地图的初始zoomLevel 设置为 3,minimumZoomLevel 设置为 0,maximumZoomLevel 设置为 3。
Map { id: map property bool panning: false anchors.fill: parent center: mapParameters.startPosition bearing: mapParameters.bearing zoomLevel: root.zoomLevel minimumZoomLevel: mapParameters.minimumZoomLevel maximumZoomLevel: mapParameters.maximumZoomLevel ...
它定义了MouseArea ,该函数负责计算pan 函数中的deltaX 和deltaY 参数。
MouseArea { id: mapPan anchors.fill: parent property real pressPointX: 0 property real pressPointY: 0 property real translationX: 0 property real translationY: 0 onPressed: { map.panning = true pressPointX = mouse.x pressPointY = mouse.y translationX = 0 translationY = 0 } onReleased: { map.panning = false } onPositionChanged: { var x = mouse.x - pressPointX var y = mouse.y - pressPointY var deltaX = x - translationX var deltaY = y - translationY translationX = x translationY = y map.pan(-deltaX, -deltaY) } }
MapParameters.qml
它定义了Map 项的默认参数。
...
readonly property real zoomLevel: 3
readonly property real minimumZoomLevel: 0
readonly property real maximumZoomLevel: 3
readonly property real bearing: 0
readonly property geoCoordinate startPosition: QtPositioning.coordinate(65.05877, 25.45545)
...MapMarker.qml
MapMarker.qml 是一个自定义的 QML 类型。它封装了 `MapQuickItem ` 项,该项在地图上表示一个兴趣点标记。
// Copyright (C) 2025 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial import QtQuick import QtLocation import QtPositioning MapQuickItem { id: root property alias markerText: markerText.text property alias imageSource: markerImage.source sourceItem: Image { id: markerImage source: "" Text { id: markerText text: "" font.pointSize: 7 font.bold: true anchors.bottom: parent.top anchors.horizontalCenter: parent.horizontalCenter } } coordinate: QtPositioning.coordinate(0, 0) anchorPoint: Qt.point(sourceItem.width / 2, sourceItem.height / 2) }
文件:
- map/+t2g/+4m/MapContainer.qml
- map/+t2g/+4m/map.qml
- map/+t2g/+6m/MapContainer.qml
- map/+t2g/+6m/map.qml
- map/+t2g/MapParameters.qml
- map/CMakeLists.txt
- map/CopyrightText.qml
- map/MapButton.qml
- map/MapContainer.qml
- map/MapMarker.qml
- map/MapParameters.qml
- map/board_config.h
- map/desktop/board_config.cpp
- map/dummy_position_source/dummypositiondata.cpp
- map/dummy_position_source/dummypositionsource.cpp
- map/dummy_position_source/dummypositionsource.h
- map/dummy_position_source/indexmanager.h
- map/map.qml
- map/mcu_map.qmlproject
- map/mcu_map_t2g_4m.qmlproject
- map/mcu_map_t2g_6m.qmlproject
- map/offline_tiles_provider/offlinetilefetcher.cpp
- map/offline_tiles_provider/offlinetilefetcher.h
- map/os/baremetal/main.cpp
- map/stm/stm32f7/board_config.cpp
- map/stm/stm32u5/board_config.cpp
- map/t2g-traveo/board_config.cpp
图片:
在某些 Qt 许可下可用。
了解更多。