本页内容

地点地图(QML)

“地点地图”示例演示了如何使用MapItemView 在地图上搜索并显示地点列表。

一张标有几处披萨店位置的地图

该示例会显示当前位置的地图;如果无法获取位置信息,则默认显示挪威奥斯陆。随后,系统会搜索与关键词“food”匹配的地点,并将每个搜索结果显示在地图上。

运行示例

您可以通过以下方式运行该示例:

要编写一个能在地图上显示地点的 QML 应用程序,我们首先需要进行以下导入声明。

import QtQuick
import QtPositioning
import QtLocation

实例化一个 `Plugin ` 实例。`Plugin ` 实际上是获取地点数据的后端。根据所选插件的不同,可能需要一些必填参数。本例中选择了OSM 插件,该插件没有必填参数。

Plugin {
    id: myPlugin
    name: "osm"
    //specify plugin parameters if necessary
    //PluginParameter {...}
    //PluginParameter {...}
    //...
}

接下来,我们实例化一个PlaceSearchModel ,用于指定搜索参数并执行地点搜索操作。为便于说明,在模型构建完成后会调用一次update()。通常情况下,update()会在响应用户操作(如点击按钮)时被调用。

PlaceSearchModel {
    id: searchModel

    plugin: myPlugin

    searchTerm: "food"
    searchArea:  QtPositioning.circle(positionSource.lastSearchPosition, 1000 /* 1 km radius */)
    Component.onCompleted: update()
}

地图通过MapView 类型显示,其中我们声明了MapItemView 方法,并传入搜索模型和一个委托。此处使用了内联委托,且我们假设每个搜索结果均为type 类型(PlaceSerachesult )。因此,我们默认始终可以访问place对象(role );而其他类型的搜索结果可能不包含place对象(role )。

MapView {
    id: view
    anchors.fill: parent
    map.plugin: myPlugin;
    map.center: positionSource.lastSearchPosition
    map.zoomLevel: 13

    MapItemView {
        model: searchModel
        parent: view.map
        delegate: MapQuickItem {
            coordinate: place.location.coordinate

            anchorPoint.x: image.width * 0.5
            anchorPoint.y: image.height

            sourceItem: Column {
                Image { id: image; source: "marker.png" }
                Text { text: title; font.bold: true }
            }
        }
    }
}

最后,通过PositionSource 将地图重置为当前位置,并在新区域内查找“美食”场所。位置信息每 2 分钟更新一次,如果新位置与上次美食搜索区域的距离超过 500 米,则会重新触发场所搜索。

PositionSource {
    id: positionSource
    property variant lastSearchPosition: QtPositioning.coordinate(59.93, 10.76) //Initialized/Fallback to Oslo
    active: true
    updateInterval: 120000 // 2 mins
    onPositionChanged:  {
        var distance = lastSearchPosition.distanceTo(position.coordinate)
        if (distance > 500) {
            // 500m from last performed food search
            lastSearchPosition = positionSource.position.coordinate
        }
    }
}

示例项目 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.