summaryrefslogtreecommitdiffstats
path: root/src/location/declarativemaps/qdeclarativegeojsondata.cpp
blob: e4a7724c6671a23982b41abdaa598be687056f1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// Copyright (C) 2019 Julian Sherollari <jdotsh@gmail.com>
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qdeclarativegeojsondata_p.h"

#include <QtLocation/private/qgeojson_p.h>

QT_BEGIN_NAMESPACE

namespace extractor
{
    static bool hasProperties(QQuickItem *item)
    {
        QVariant props = item->property("props");
        return !props.isNull();
    }

    static QVariant toVariant(QObject *mapItem)
    {
        if (QDeclarativeGeoMapItemView *miv = qobject_cast<QDeclarativeGeoMapItemView *>(mapItem)) {
            return toVariant(miv);
        } else if (QDeclarativePolylineMapItem *polyline = qobject_cast<QDeclarativePolylineMapItem *>(mapItem)) {
            return toVariant(polyline);
        } else if (QDeclarativePolygonMapItem *polygon = qobject_cast<QDeclarativePolygonMapItem *>(mapItem)) {
            return toVariant(polygon);
        } else if (QDeclarativeCircleMapItem *circle = qobject_cast<QDeclarativeCircleMapItem *>(mapItem)) {
            return toVariant(circle); // If GeoJSON Point type is visualized in other ways, handle those types here instead.
        } else if (QDeclarativeRectangleMapItem *rectangle = qobject_cast<QDeclarativeRectangleMapItem *>(mapItem)) {
            return toVariant(rectangle); // For the self-drawn rectangles. Will be exported as Polygons
        }
        return QVariant();
    }

    static QVariantMap toVariant(QDeclarativePolygonMapItem *mapPolygon)
    {
        QVariantMap ls;
        ls[QStringLiteral("type")] = QStringLiteral("Polygon");
        ls[QStringLiteral("data")] = QVariant::fromValue(mapPolygon->geoShape());
        if (hasProperties(mapPolygon))
            ls[QStringLiteral("properties")] = mapPolygon->property("props").toMap();
        return ls;
    }

    static QVariantMap toVariant(QDeclarativePolylineMapItem *mapPolyline)
    {
        QVariantMap ls;
        ls[QStringLiteral("type")] = QStringLiteral("LineString");
        ls[QStringLiteral("data")] = QVariant::fromValue(mapPolyline->geoShape());
        if (hasProperties(mapPolyline))
            ls[QStringLiteral("properties")] = mapPolyline->property("props").toMap();
        return ls;
    }

    static QVariantMap toVariant(QDeclarativeCircleMapItem *mapCircle)
    {
        QVariantMap pt;
        pt[QStringLiteral("type")] = QStringLiteral("Point");
        pt[QStringLiteral("data")] = QVariant::fromValue(mapCircle->geoShape());
        QVariantMap propMap = mapCircle->property("props").toMap();
        propMap[QStringLiteral("radius")] = mapCircle->radius();
        pt[QStringLiteral("properties")] = propMap;
        return pt;
    }

    static QVariantMap toVariant(QDeclarativeRectangleMapItem *mapRectangle)
    {
        QVariantMap pt;
        pt[QStringLiteral("type")] = QStringLiteral("Polygon");
        QGeoRectangle rectanlge = mapRectangle->geoShape();
        QGeoPolygon poly;
        poly.addCoordinate(rectanlge.topLeft());
        poly.addCoordinate(rectanlge.topRight());
        poly.addCoordinate(rectanlge.bottomRight());
        poly.addCoordinate(rectanlge.bottomLeft());
        pt[QStringLiteral("data")] = QVariant::fromValue(poly);
        if (hasProperties(mapRectangle))
            pt[QStringLiteral("properties")] = mapRectangle->property("props").toMap();
        return pt;
    }
};


/*!
    \qmltype GeoJsonData
    \instantiates QDeclarativeGeoJsonData
    \inqmlmodule QtLocation
    \ingroup qml-QtLocation5-maps
    \since QtLocation 6.7

    \brief A model to represent, load and save GeoJSON documents.


    The GeoJsonData element reads and writes GeoJson documents
    (see the \l {https://en.wikipedia.org/wiki/GeoJSON}
    {Wikipedia page}, \l {https://tools.ietf.org/html/rfc7946} {RFC}) from
    the \l {sourceUrl}.
    The respective data can be accessed as \l {QVariant} via the \l {model} property.
    The \l {QVariant} representation can be used with delegates to visualize
    the data or to make small modifications, e.g. adding new items with the
    \l {addItem} function.

    New data can be stored with the \l {save} and \l {saveAs} functions.

    \sa QGeoJson
*/


QDeclarativeGeoJsonData::QDeclarativeGeoJsonData(QObject *parent)
    : QObject(parent)
{

}

QDeclarativeGeoJsonData::~QDeclarativeGeoJsonData()
{

}

/*!
    \qmlproperty QVariant QtLocation::GeoJsonData::model

    A \l QVariant representation of the GeoJSON document that
    can be used to display the contents with delegates.

    \since 6.7
*/
QVariant QDeclarativeGeoJsonData::model() const
{
    return m_content;
}

void QDeclarativeGeoJsonData::setModel(const QVariant &model)
{
    m_content = model;
    emit modelChanged();
}


/*!
    \qmlproperty QUrl QtLocation::GeoJsonData::sourceUrl

    The URL from which the GeoJSON document is read. Setting this
    property will change the \l model to represent the respective document.

    \since 6.7
*/


QUrl QDeclarativeGeoJsonData::sourceUrl() const
{
    return m_url;
}

/*!
    \qmlmethod void QtLocation::GeoJsonData::clear()

    Delete all items in the \l model of the GeoJsonData.
*/
void QDeclarativeGeoJsonData::clear()
{
    m_content = QVariantList();
    emit modelChanged();
}

/*!
    \qmlmethod bool QtLocation::GeoJsonData::addItem(Item item)

    Add the \a item to the \l model of the GeoJsonData.

    Returns \c true if the file was read successfully, \c false otherwise.
*/
void QDeclarativeGeoJsonData::addItem(QQuickItem *item)
{
    QVariant entry;
    if (auto *polyline = qobject_cast<QDeclarativePolylineMapItem *>(item))
        entry = extractor::toVariant(polyline);
    else if (auto *polygon = qobject_cast<QDeclarativePolygonMapItem *>(item))
        entry = extractor::toVariant(polygon);
    else if (auto *circle = qobject_cast<QDeclarativeCircleMapItem *>(item))
        entry = extractor::toVariant(circle);
    else if (auto *rectangle = qobject_cast<QDeclarativeRectangleMapItem *>(item))
        entry = extractor::toVariant(rectangle);
    else
        return;

    QVariantList geoJson = m_content.toList();
    if (!geoJson.isEmpty()){
        QVariantList geoData = (geoJson[0].toMap()[QStringLiteral("type")] == QStringLiteral("FeatureCollection")) ? geoJson[0].toMap()[QStringLiteral("data")].toList() : geoJson;
        geoData.append(entry);
        geoJson[0] = QVariantMap{{QStringLiteral("type"), QStringLiteral("FeatureCollection")}, {QStringLiteral("data"), geoData}};
    }
    else {
        geoJson.append(entry);
    }
    m_content = geoJson;
    emit modelChanged();
}

/*!
    \qmlmethod bool QtLocation::GeoJsonData::open()

    Reload the content of the file at \l sourceUrl.

    Returns \c true if the file was read successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::open()
{
    return openUrl(m_url);
}

/*!
    \qmlmethod bool QtLocation::GeoJsonData::openUrl(Url url)

    Open the GeoJson file at \a url and load its content. The property
    \l sourceUrl will be set to \a url if the file is read successfully.

    Returns \c true if the file was read successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::openUrl(const QUrl &url)
{
    // Reading GeoJSON file
    QFile loadFile(url.toLocalFile());
    if (!loadFile.open(QIODevice::ReadOnly)) {
        qWarning() << "Error while opening the file: " << url;
        qWarning() << loadFile.errorString();
        return false;
    }

    // Load the GeoJSON file using Qt's API
    QJsonParseError err;
    QJsonDocument loadDoc(QJsonDocument::fromJson(loadFile.readAll(), &err));
    if (err.error) {
         qWarning() << "Parsing while importing the JSON document:\n" << err.errorString();
         return false;
    }

    // Import geographic data to a QVariantList
    m_content = QGeoJson::importGeoJson(loadDoc);
    if (m_url != url) {
        m_url = url;
        emit sourceUrlChanged();
    }
    emit modelChanged();
    return true;
}

/*!
    \qmlmethod bool QtLocation::GeoJsonData::saveAs(Url url)

    The current \l model of the GeoJsonData object is saved under \a url.
    The \l sourceUrl property will be set to \a url.

    Returns \c true if the file was saved successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::saveAs(const QUrl &url)
{
    if (m_url != url){
        m_url = url;
        emit sourceUrlChanged();
    }
    return save();
}

/*!
    \qmlmethod bool QtLocation::GeoJsonData::save()

    The current \l model of the GeoJsonData object is saved under
    \l sourceUrl.

    Returns \c true if the file was saved successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::save()
{
    return dumpGeoJSON(m_content.toList(), m_url);
}

/*!
    \qmlmethod void QtLocation::GeoJsonData::setModelToMapContents(MapView mapItemView)

    All mapItems of \a mapItemView are added to the \l model of the GeoJsonData
    object.
    Previously stored mapItems are deleted from the \l model.

    Returns \c true if mapItemView is set successfully, \c false otherwise.

    \sa addItem
*/
void QDeclarativeGeoJsonData::setModelToMapContents(QDeclarativeGeoMap *map)
{
    m_content = toVariant(map);
    emit modelChanged();
}

/*! \internal
    A helper function to convert the children of a map to a \l QVariantList that
    represents the items and that can be exported to a Json file.

    Returns a \l QVariantList containing all data of the mapItems.
*/
QVariantList QDeclarativeGeoJsonData::toVariant(QDeclarativeGeoMap *map)
{
    QVariantList res;
    const QList<QObject*> mapChildren = map->children();
    for (QObject *child : mapChildren) {
        QVariant mapItemAsVariant = extractor::toVariant(child);
        if (mapItemAsVariant.isValid())
            res.append(mapItemAsVariant);
    }
    return res;
}

/*! \internal
    A helper function to dump the VariantList \a geoJson into the file at \a url.

    Returns \c true if the file was saved successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::dumpGeoJSON(const QVariantList &geoJson, const QUrl &url)
{
    QJsonDocument json = QGeoJson::exportGeoJson(geoJson);
    QFile jsonFile(url.toLocalFile());
    if (!jsonFile.open(QIODevice::WriteOnly))
        return false;
    jsonFile.write(json.toJson());
    jsonFile.close();
    return true;
}

/*! \internal
    A helper function to write a human interpretable representation of
    \a geoJson into the file at \a url.

    Returns \c true if the file was saved successfully, \c false otherwise.
*/
bool QDeclarativeGeoJsonData::writeDebug(const QVariantList &geoJson, const QUrl &url)
{
    QString prettyPrint = QGeoJson::toString(geoJson);
    QFile debugFile(url.toLocalFile());
    if (!debugFile.open(QIODevice::WriteOnly))
        return false;
    debugFile.write(prettyPrint.toUtf8());
    debugFile.close();
    return true;
}

/*! \internal
    A helper function to generate a human interpretable representation of
    \a geoJson.

    Returns a string with the human interpretable representation of \a geoJson.
*/
QString QDeclarativeGeoJsonData::toString(const QVariantList &geoJson)
{
    return QGeoJson::toString(geoJson);
}

QT_END_NAMESPACE