2016-01-06 616 views
1

我使用QML Creator(Community)5.5.1支持QML項目。 我有這樣的代碼:QML-maps:點擊屏幕時獲取座標

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 

    } 

我該如何將標記定位在發生點擊的座標上的地圖上?謝謝。

回答

2

剛剛成立的的coordinateonPressed處理。類似以下內容:

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)) 
     } 
    } 
} 
+0

謝謝!但是如果我在地圖上沒有任何標記,它會成爲新標記?我能怎麼做? – Khan

+0

@Khan,你的目標是擁有一個標記嗎?你是否希望它只在點擊發生時出現?如果是這樣,那麼如何將標記的「visible」設置爲false,然後在'onPressed'手柄中將其設置爲true。 – nfranklin

+0

如果您想「創建」每個新點擊的新標記,請查看[動態對象創建文檔](http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html)..或更好的是,使用模型(添加點擊位置的地方)和[MapItemView](http://doc.qt.io/qt-5/qml-qtlocation-mapitemview.htm) – nfranklin