Brykyz
Brykyz

Reputation: 657

QML Map not giving any coordinates when component completes

i'm trying to get two coordinates from QML component Map. I tried to use standard Component.onCompleted. I am trying to get the coordinate that is at the top left and the coordinate that is at the bottom right.

I'm using Map function toCoordinate with Qt.Point() as a parameter.

Problem occurs when function is called, because output of this function is empty.

I am using Qt 5.12.3.

Output:

qml: 
qml: 

My code

import QtQuick 2.12
import QtQuick.Window 2.12
import QtLocation 5.9
import QtPositioning 5.3

Window {
    visible: true
    width: 640
    height: 480

    Map {
        id: map
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        height: parent.height + 20

        plugin: mapPlugin
        gesture.acceptedGestures: {
                    MapGestureArea.PanGesture      |
                    MapGestureArea.PinchGesture
        }

        Component.onCompleted: {
            console.log(map.toCoordinate(Qt.point(0,0)))
            console.log(map.toCoordinate(Qt.point(map.width, map.height)))
        }
    }

    Plugin {
        id: mapPlugin
        name: "osm"

        PluginParameter {
            name: "osm.mapping.cache.directory"
            value: "./cache/"
        }
    }
}

Is there any solution for this problem? Did anyone have similiar problem?

Thank you for your help.

//Edit:

When I use map.toCoordinate(Qt.point(0,0)) in Map.onCenterChanged and then move with Map, it returns valid coordinate.

Upvotes: 1

Views: 1824

Answers (1)

eyllanesc
eyllanesc

Reputation: 244232

As the docs points out:

mapReady : bool

This property holds whether the map has been successfully initialized and is ready to be used. Some methods, such as fromCoordinate and toCoordinate, will not work before the map is ready. Due to the architecture of the Map, it's advised to use the signal emitted for this property in place of Component.onCompleted, to make sure that everything behaves as expected.

(The emphasis is mine)

Component.onCompleted does not guarantee that the map is rendered or has the information provided by the API, instead you must use the mapReady property:

Map {
    id: map
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    height: parent.height + 20

    plugin: mapPlugin
    gesture.acceptedGestures: {
        MapGestureArea.PanGesture |
        MapGestureArea.PinchGesture
    }

    onMapReadyChanged: {
        if(mapReady){
            console.log(map.toCoordinate(Qt.point(0,0)))
            console.log(map.toCoordinate(Qt.point(map.width, map.height)))
        }
    }
}

Output:

qml: 51° 32' 29.3" N, 1° 53' 7.8" W, 0m
qml: 51° 28' 23.1" N, 1° 37' 48.4" E, 0m

Upvotes: 2

Related Questions