地点地图(QML)

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

该示例显示当前位置的地图,如果没有可用位置,则使用奥斯陆/挪威地图。然后搜索与 "食品 "一词相匹配的地点,并将每个结果显示在地图上。

运行示例

运行示例 Qt Creator,打开Welcome 模式并从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行

要编写在地图上显示地点的 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 。因此,我们假定总是可以访问role ,其他搜索结果类型可能没有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

© 2025 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.