How to dynamically add map objects to QML MAP element? Or how to create customised Map widget?



  • Hi,

    I am implementing an application with a rather complicated UI, which has at least 4 views and each view contains widgets like button, slider bar etc. Therefore I want very much to use QML to handle the view and graphics layout management.

    However, my application(at least two of views) would need showing a map widget and loading map objects(such as circls, texts, images) dynamically at runtime during application start up. I have browsed some previous threads regarding this issue, and it seems there is difficult to do this with QML Map element at the moment.

    I have tested following code in QML:
    @Map {
    id: map
    plugin : Plugin {
    name : "nokia"
    }

            anchors.fill: parent
    
            size.width: parent.width
    
            size.height: parent.height
            
            zoomLevel: t_data.zoomLevel
    
            center: Coordinate {latitude: 46.5; longitude: 6.6}
    
            objects: t_data.mapObjectsList
    
    
            onZoomLevelChanged: {
                console.log("Zoom changed")
            }
    
        } // map
    

    @
    On C++ side:

    @class TestData : public QObject
    {
    Q_OBJECT
    Q_PROPERTY(qreal zoomLevel READ zoomLevel WRITE setZoomLevel NOTIFY zoomLevelChanged)
    Q_PROPERTY(QDeclarativeListProperty<QGeoMapObject> mapObjectsList READ mapObjectsList)

    public:
    ...
    qreal zoomLevel() const{return mZoomLevel;};
    QDeclarativeListProperty<QGeoMapObject> mapObjectsList(){return QDeclarativeListProperty<QGeoMapObject>(this, mls);};

    private:
    qreal mZoomLevel;
    QList<QGeoMapObject*> mls;

    }@

    And the result is I could set the map zoom level at runtime, but the map objects list is NOT loaded, and no map object was displayed in QML.

    I read in earlier threads suggesting to subclass QGeoGraphicsMap and created customised Map widget, then exposed this widget to QML. However, the QGeoGraphicsMap requires QGeoMappingManager instance at the initilizing phase, and I assume that the graphic widget exposed to QML should avoid it, and could be initilized without parameter. Besides I am not very familiar with the Qt graphics widget, should I reimplement some other function like paint()??

    Does someone have the experience of a customised map widget subclassing QGeoGraphicsMap which could be used in QML? Can you share some code? :-)

    Basically I want to have a map widget and adding map objects to it when application is starting, then QML will use this map widget in different views.

    Thank you very much!

    Regards,
    Juan

    EDIT: added @ tags by vcsala



  • The QML Map item in the master branch of the git repository has addMapObject(...) and removeMapObject(....) methods.

    If you're stuck with a version of Qt Mobility which doesn't have those methods then it's going to be very painful.

    My understanding is something like this (although it's been a while since it was explained to me): You can't just assign the list of map objects across, so you'll probably have to maintain your own array of map objects in javascript and then clear and re add the objects to the list of map objects any time that array changes.

    You could always write your own QML map item, and that shouldn't require the subclassing of QGeoGraphicsMap, since you can do it all from QGeoMapData and QGeoMappingManager (which can be initialized by the Plugin item).

    Anyhow, if you can use the code from master or if you can wait for the Qt Mobility 1.2 release I'd probably recommend that pretty highly.



  • Hi,

    Thank you very much for the reply!

    I am using qt mobility 1.1 beta, I wonder if there is version 1.2 for internal download and use?

    I have read the documentation of qt mobility 1.2 related to location API part, and I am aware of the addMapObject(MapObject) and removeMapObject(MapObject). But I'm not quite sure whether they are really for adding/removing map objects dynamically...

    It seems the parameter used in this two functions is MapObject, which is a QML element. And I understood that instead of putting the MapObject as a child element of Map element, you could have the MapObject outside Map element scope, and add the MapObject to the map at runtime. However, with this approach, one still needs to know how many map objects will be loaded at runtime, and predefine the MapObject element for them in QML. For example, one has to know there will be two map circles created at runtime , then create following qml:
    @MapCircle {
    id: circle1
    center: coordinate1
    radius: 100
    color: "yellow"
    }
    MapCircle {
    id: circle2
    center: coordinate1
    radius: 100
    color: "yellow"
    }

    ...
    onButton2Clicked: {
    map.addMapObject(circle1)

     map.addMapObject(circle2)
    

    }@

    And if you actually have 3 map circles need to be drawn, the addMapObject(MapObject) can not be used to add the circle3.

    On the other hand, you could always have the two map circles as map child elements, and set the visibility at runtime, and make it looks like adding/removing object from map.

    I am very grateful to be answered by Location API team, and could you clarify a bit more on how to use add/remove map object in QML Map element? I undertood the mobility API version 1.2 will be released pretty soon, and I can waite if it provides features which my application would need.

    I prefer using qml map element to creating customised map widget, because I might run into some strange bugs if I use my own widget which I have no clue how to solve it. But I would also like to be clear what qml offers, and use it in a best way.

    Regards,
    Juan Feng
    Contextual Solutions team
    Nokia Research Center



  • Hi Juan,

    since I have been through the same pain I thought I should share my solution with you. It's probably a hack, but it works for me.

    Basically I've created a subclass of QGraphicsGeoMap that mostly just wraps the API and exposes some methods to QML that are not available by default.

    You are right that we need to have a parameter-less constructor to be able to use that widget within QML. Also you're right, QGraphicsGeoMap does not have a parameter-less constructor. I've solved that by having a static method that will provided the needed parameter. See MapWidget::createManager()

    I'll simply paste my code below. Please note that I've not taken the time to make this code work stand-alone. It's ripped out of one of my projects and I removed as many unnecessary things to not further confuse you. I hope you can get the general idea from that code.

    Have a look at addPoi() and removePoi() and createManager(). If you would like to use addPoi() directly from QML, you should change the signature to something like this:
    @ Q_INVOCABLE void addPoi(double lat, double lon); @

    In my main.cpp I'm doing the following:
    @ qmlRegisterType<MapWidget>("mywidgets", 1, 0, "TsMap"); @

    Have fun :)

    @
    // map_widget.h
    #ifndef MAP_WIDGET_H
    #define MAP_WIDGET_H

    #include <QGraphicsGeoMap>
    #include <QGeoMappingManager>
    #include <QGeoMapCircleObject>
    #include <QGeoMapObject>
    #include <QGeoMapPixmapObject>

    #include "poi_list_model.h"
    #include "data_manager.h"

    QTM_USE_NAMESPACE

    class MapWidget : public QGraphicsGeoMap
    {
    Q_OBJECT

    public:
    MapWidget();
    ~MapWidget();

    void addPoi(PoiData *poi, bool active);
    void removePoi(PoiData *poi);
    void clearPois();
    

    signals:
    void poiClicked(QString uuid);

    protected:
    void mousePressEvent(QGraphicsSceneMouseEvent* event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent* event);
    void mouseMoveEvent(QGraphicsSceneMouseEvent* event);

    private:
    static QGeoMappingManager* createManager();
    };

    #endif // MAP_WIDGET_H
    @



  • @
    // map_widget.cpp
    #include <QDebug>
    #include <QGeoServiceProvider>
    #include <QGeoMappingManager>
    #include <QGeoCoordinate>
    #include <QGeoMapCircleObject>
    #include <QGeoMapPixmapObject>
    #include <QGeoMapGroupObject>
    #include <QGraphicsSceneMouseEvent>
    #include <QGeoBoundingBox>
    #include <QtCore>

    #include "map_widget.h"

    // A widget for QML, therefore we need the parameter-less constructor.
    MapWidget::MapWidget() :
    QGraphicsGeoMap(createManager())
    {
    setCenter(QGeoCoordinate(51.05, 13.73));
    setZoomLevel(17);
    }

    MapWidget::~MapWidget()
    {
    }

    // This method is a bit a heck. We actually call it before the object
    // is completely created. We need to do this, because our parent class
    // needs a QGeoMappingManager passed to its constructor.
    QGeoMappingManager* MapWidget::createManager()
    {
    qDebug() << "INFO: Creating mapping manager";
    // We have to access this as static member, because we can't get anything
    // inside this object from the outside. The reason is, that this method
    // is called by the constructor and that we cannot add values to the
    // constructor, because QML always needs a parameter-less constructor.
    QGeoServiceProvider *serviceProvider = new QGeoServiceProvider("osm", params);
    QGeoMappingManager *mappingManager = serviceProvider->mappingManager();
    if (mappingManager == 0) {
    qDebug() << "WARN: Could not load 'osm' plugin. Falling back to 'nokia' plugin.";
    serviceProvider = new QGeoServiceProvider("nokia");
    mappingManager = serviceProvider->mappingManager();
    }

    return mappingManager;
    

    }

    void MapWidget::addPoi(PoiData *poi, bool active)
    {
    QGeoCoordinate coord(poi->getLat(), poi->getLon());

    QPixmap pixmap;
    if (active) {
        pixmap = QPixmap(":qml/Common/img/poi_active.png");
    } else {
        pixmap = QPixmap(":qml/Common/img/poi_inactive.png");
    }
    
    QGeoMapPixmapObject *pixMapObject = new QGeoMapPixmapObject(coord, QPoint(-26,-65), pixmap);
    pixMapObject->setProperty("uuid", poi->getUuid());
    pixMapObject->setObjectName("poiMarker");
    
    QGeoMapGroupObject *poiMarker = new QGeoMapGroupObject();
    poiMarker->setProperty("uuid", poi->getUuid());
    poiMarker->addChildObject(pixMapObject);
    
    if (active) {
        QGeoMapCircleObject *circle = new QGeoMapCircleObject(coord, poi->getRadius());
        circle->setPen(QPen((poiColor)));
        circle->setBrush(QBrush(poiColor));
        circle->setZValue(-1);
        poiMarker->addChildObject(circle);
    }
    
    addMapObject(poiMarker);
    

    }

    void MapWidget::removePoi(PoiData *poi)
    {
    for (int i = 0; i < poiMarkers.length(); ++i) {
    QGeoMapObject *marker = poiMarkers[i];
    if (marker->property("uuid").toString() == poi->getUuid()) {
    removeMapObject(marker);
    return;
    }
    }
    }

    void MapWidget::clearPois()
    {
    for (int i = 0; i < poiMarkers.length(); ++i) {
    QGeoMapObject *obj = poiMarkers[i];
    removeMapObject(obj);
    }
    }

    /*

    • Remember the position. We use this in mouseReleaseEvent
      /
      void MapWidget::mousePressEvent(QGraphicsSceneMouseEvent
      event)
      {
      lastPos = event->pos();
      }

    /*

    • If the mouse was moved by a maximum of 30px between press and release

    • we look at the press coordinates and if there is a POI we emit a signal

    • if there are several POIs, we only emit the signal for the first one.
      /
      void MapWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent
      event)
      {
      QPointF newPos = event->pos();
      QPointF diff = lastPos - newPos;

      if (qAbs(diff.x()) > 30 || qAbs(diff.y()) > 30) {
      return;
      }

      QList<QGeoMapObject*> objects = mapObjectsAtScreenPosition(lastPos);
      if (objects.length() > 0) {
      for (int i = 0; i < objects.length(); i++) {
      QGeoMapObject *obj = objects[i];
      if (obj->objectName() == "poiMarker") {
      QString uuid = obj->property("uuid").toString();
      emit poiClicked(uuid);
      }
      }
      }
      }

    void MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
    {
    // Round to int
    QPoint lastPos = event->lastPos().toPoint();
    QPoint pos = event->pos().toPoint();

    int dx = lastPos.x() - pos.x();
    int dy = lastPos.y() - pos.y();
    
    pan(dx, dy);
    setFollowPosition(false);
    

    }
    @



  • JuanF: please use @ tags around your code snippets to make it more readable (I have edited your posts in this thread)



  • Hi Conny,

    Thank you very much!

    Your approach does work! I think for developers who need to use more complicated features than what qml location plugin offers, probably a custimised map widget which extends QGraphicsGeoMap is the best option.

    And it is also possible to develope own map widget, which subclasses QGraphicsWidget, by using QGeoMapData and QGeoMappingManager.

    Thanks again!

    Regards,
    Juan



  • You're welcome! I'm glad I could help :)



  • Hi Conny and Juan,

    Would you just post som QML example how do you use tat MapWidget in QML. Im new in QML/Qt wold.

    Many Thanks



  • Hi Jano,

    if you're new with QML you should start by using the default map item. It has also much improved in QtM 1.2. Have a look here:
    http://doc.qt.nokia.com/qtmobility-1.2/declarative-location-mapviewer-mapviewer-qml.html



  • Hi i tried your example.

    Map is succesfully created and pois are shown.. But im not receiving any mousevents.. :(



  • Actually, im getting mouse events only on device but no in Simulator. Did u have same issue?

    Many Thanks!



  • I've not used the simulator for quite some time and currently still have only an old version installed, so I don't know. All I know is that you need at least QtM 1.2. If you have this and it's still not working I'd say it's a bug and you should report it.



  • Hi Conny,

    I resolve issue. I'm gettin mouse events in simulator aswell.

    Do you maybe know if is possible to add mapObject to the map so that onclick event can be handled?
    Somehow extend QGeoMapObject?

    Unfortunatelly method mapObjectsAtScreenPosition(lastPos) does not work on devices. I'm retreiving empty objects lists.

    see bug: http://bugreports.qt.nokia.com/browse/QTMOBILITY-841?page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel

    I have latest Qt SDK 1.1.2 and usign Qt Mobility 1.1

    Many Thanks for your help



  • Yes you're right. Actually I've reported that bug. Unfortunately I don't know a way to get the mouse events on a devices with QtM < 1.2. I'm also waiting that QtM 1.2 will finally be available for devices.

    On Maemo5 I've tested it with QtM 1.2 and it's actually working. On Symbian and for Ovi, we still have to wait :(



  • Conny,

    Thaks again for your help. I resolved the issue.

    I'm checking mapObjects boundingBox and check if contains clicked coordinate.

    Regards



  • Sounds like a good work-around. Very nice!

    Thanks for sharing!
    Conny



  • Nice! I have also decided to give qml a try and of course are running into the same issues. I have started to make a minimal demo app from conny's example and would like to setup a wiki page or similar as i think we should document this a little bit, so others can re-use this.



  • harabaum,

    Please post link here, when u are done with demo :)

    Regards



  • Ok, "here":http://wiki.meego.com/QML/QGraphicsGeoMap is the wiki page. Please contribute your findings and let's try to make this into a small complete guide for this. I e.g. found that the map doesn't scale when the window size changes.



  • Thanks Till,
    what problems do you have with scaling? If I anchor the map to the QML root item and then scale the window the map size is increased. What's the result you get?



  • The map just doesn't scale with the window. These are my very first minutes with qml, so i may just be missing something. What do you e.g. mean by anchoring? Would you mind changing the appropriate parts in the wiki page?



  • Ah ok, just try this:

    @
    Rectangle {
    id: page
    anchors.fill: parent

    Map {
    anchors.fill: parent
    }
    }
    @

    Ok, now you won't see the rectangle anymore, but you get the point.



  • Also you might need the following in main.cpp:
    @
    view.setResizeMode(QDeclarativeView::SizeRootObjectToView);
    @

    That will always scale the root QML item to the size of the QDeclarativeView.



  • Thanks, Conny. With these two changes, the map scales nicely!

    And feel free to do changes/extensions to the wiki yourself :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.