QML地图:在屏幕上轻触时获取坐标

5
我是一位有用的助手,可以为您翻译文本。
我正在使用支持QML的Qt Creator(Community)5.5.1制作项目。 我有以下代码:
main.qml:
MouseArea
        {   anchors.fill: parent
            onPressed: console.log('latitude = '+ (map.toCoordinate(Qt.point(mouse.x,mouse.y)).latitude),
                                   'longitude = '+ (map.toCoordinate(Qt.point(mouse.x,mouse.y)).longitude));

当我点击屏幕时,这个地方在地图上的坐标会显示在控制台上。但我不知道如何使用这些坐标将标记放置在发生点击的屏幕位置上。这是标记代码:

MapQuickItem {
        id:marker
        coordinate:  QtPositioning.coordinate(******, ******);//stars are the coordinates
        sourceItem: Image{
            id: image
            source: "marker2.png"

        }
        anchorPoint.x: image.width / 2
        anchorPoint.y: image.height

    }

我应该怎么做才能将标记放置在点击发生的坐标位置上?谢谢。

1个回答

5

只需在 onPressed 处理程序中设置 markercoordinate 即可。类似以下内容:

import QtQuick 2.0
import QtLocation 5.5

Map {
    id: map
    plugin: Plugin {name: "osm"}
    zoomLevel: (maximumZoomLevel - minimumZoomLevel)/2
    center {
        // The Qt Company in Oslo
        latitude: 59.9485
        longitude: 10.7686
    }

    MapQuickItem {
        id:marker
        sourceItem: Image{
            id: image
            source: "marker2.png"

        }
        coordinate: map.center
        anchorPoint.x: image.width / 2
        anchorPoint.y: image.height / 2
    }

    MouseArea {
        anchors.fill: parent
        onPressed: {
            marker.coordinate = map.toCoordinate(Qt.point(mouse.x,mouse.y))
        }
    }
}

谢谢!但是如果地图上没有标记,那么怎么办呢?我该怎么做? - Khan
@Khan,你的目标是要有一个单一的标记吗?你希望它只在点击发生时出现吗?如果是这样,那么将标记的“visible”设置为false,然后在“onPressed”处理程序中将其设置为true如何? - nfranklin
如果你想要在每次点击时“创建”新的标记,请查看动态对象创建文档。或者更好的方法是,使用一个模型(在其中添加被点击的位置)和MapItemView - nfranklin
非常感谢!但是请注意:marker.coordinate不是变量。我该如何在main.cpp中使用它?这是最后一个问题了。 - Khan
@Khan,我不明白你的问题。你是想了解如何从C++与QML对象进行交互吗?如果是这样,请参阅文档(例如这里这里)。也许最好你创建一个新的问题。 - nfranklin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接