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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693 | /* ============================================================
*
* This file is a part of digiKam project
* https://www.digikam.org
*
* Date : 2023-05-15
* Description : geolocation engine based on Marble.
* (c) 2007-2022 Marble Team
* https://invent.kde.org/education/marble/-/raw/master/data/credits_authors.html
*
* SPDX-FileCopyrightText: 2023-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
* ============================================================ */
#include "JsonParser.h"
// Qt includes
#include <QIODevice>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QColor>
// Local includes
#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "GeoDataPolygon.h"
#include "GeoDataLinearRing.h"
#include "GeoDataPoint.h"
#include "GeoDataMultiGeometry.h"
#include "GeoDataStyle.h"
#include "GeoDataIconStyle.h"
#include "GeoDataLineStyle.h"
#include "GeoDataPolyStyle.h"
#include "GeoDataLabelStyle.h"
#include "MarbleDirs.h"
#include "StyleBuilder.h"
#include "OsmPlacemarkData.h"
#include "digikam_debug.h"
namespace Marble
{
/**
The JsonParser class reads in a GeoJSON document that conforms to
RFC7946 (including relevant errata) and optionally contains
attributes from the Simplestyle specification version 1.1.0
((https://github.com/mapbox/simplestyle-spec). Attributes are also
stored as OSM tags as required.
TODO: Handle the Simplestyle "marker-size", "marker-symbol" and
"marker-color" correctly.
*/
JsonParser::JsonParser()
: m_document(nullptr)
{
// Get the default styles set by Marble
GeoDataPlacemark placemark;
GeoDataStyle::Ptr style(new GeoDataStyle(*(placemark.style())));
m_iconStylePoints = new GeoDataIconStyle(style->iconStyle());<--- Class 'JsonParser' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).<--- Class 'JsonParser' does not have a operator= which is recommended since it has dynamic memory/resource allocation(s).
m_iconStyleOther = new GeoDataIconStyle(style->iconStyle());
m_lineStyle = new GeoDataLineStyle(style->lineStyle());
m_polyStyle = new GeoDataPolyStyle(style->polyStyle());
m_labelStyle = new GeoDataLabelStyle(style->labelStyle());
// Set default styles for GeoJSON objects using Simplestyle specification 1.1.0
// Set "marker-color": "#7e7e7e" and "marker-size": "medium"
m_iconStylePoints->setColor(QColor("#ff7e7e7e"));
m_iconStylePoints->setIconPath(MarbleDirs::path(QStringLiteral("svg/dot-circle-regular.svg")));
m_iconStylePoints->setSize(QSize(22, 22), Qt::KeepAspectRatio);
m_iconStyleOther->setIconPath(QString());
m_iconStyleOther->setColor(QColor("#ff7e7e7e"));
// Set "stroke": "#555555", "stroke-opacity": 1.0 and "stroke-width": 2 (increased to 2.5 due
// to problems with antialiased lines disappearing on drawn maps
m_lineStyle->setColor(QColor("#ff555555"));
m_lineStyle->setWidth(2.5);
// Set "fill": "#555555" and "fill-opacity": 0.6
m_polyStyle->setColor(QColor("#99555555"));
// Set visual properties not part of the Simplestyle spec
m_labelStyle->setColor(QColor("#ff000000"));
m_labelStyle->setGlow(true);
m_polyStyle->setFill(true);
m_polyStyle->setOutline(true);
}
JsonParser::~JsonParser()
{
delete m_document;
delete m_iconStylePoints;
delete m_iconStyleOther;
delete m_lineStyle;
delete m_polyStyle;
delete m_labelStyle;
}
GeoDataDocument* JsonParser::releaseDocument()
{
GeoDataDocument* document = m_document;
m_document = nullptr;
return document;
}
bool JsonParser::read(QIODevice* device)
{
// Release the previous document if required
delete m_document;
m_document = new GeoDataDocument;
Q_ASSERT(m_document);
// Read JSON file data
QJsonParseError error;
const QJsonDocument jsonDoc = QJsonDocument::fromJson(device->readAll(), &error);
if (jsonDoc.isNull())
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Error parsing GeoJSON:" << error.errorString();
return false;
}
else if (! jsonDoc.isObject())
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Invalid file, does not contain a GeoJSON object";
return false;
}
// Valid GeoJSON documents may not always contain a FeatureCollection object with subsidiary
// Feature objects, or even a single Feature object: they might contain just a single geometry
// object. Handle such cases by creating a wrapper Feature object if required.
const QString jsonObjectType = jsonDoc.object().value(QStringLiteral("type")).toString();
if (jsonObjectType == QStringLiteral("FeatureCollection")
|| jsonObjectType == QStringLiteral("Feature"))
{
// A normal GeoJSON document: parse it recursively
return parseGeoJsonTopLevel(jsonDoc.object());
}
else
{
// Create a wrapper Feature object and parse that
QJsonObject jsonWrapper;
QJsonObject jsonWrapperProperties;
jsonWrapper[QLatin1String("type")] = QStringLiteral("Feature");
jsonWrapper[QLatin1String("geometry")] = jsonDoc.object();
jsonWrapper[QLatin1String("properties")] = jsonWrapperProperties;
return parseGeoJsonTopLevel(jsonWrapper);
}
}
bool JsonParser::parseGeoJsonTopLevel(const QJsonObject& jsonObject)
{
// Every GeoJSON object must have a case-sensitive "type" member (see RFC7946 section 3)
const QString jsonObjectType = jsonObject.value(QStringLiteral("type")).toString();
if (jsonObjectType == QStringLiteral("FeatureCollection"))
{
// Handle the FeatureCollection object, which may contain multiple Feature objects in it
const QJsonArray featureArray = jsonObject.value(QStringLiteral("features")).toArray();
for (int featureIndex = 0; featureIndex < featureArray.size(); ++featureIndex)
{
if (! parseGeoJsonTopLevel(featureArray[featureIndex].toObject()))
{
return false;
}
}
return true;
}
else if (jsonObjectType == QStringLiteral("Feature"))
{
// Handle the Feature object, which contains a single geometry object and possibly
// associated properties. Note that only Feature objects can have recognised properties.
QVector<GeoDataGeometry*> geometryList; // Populated by parseGeoJsonSubLevel()
bool hasPoints = false; // Populated by parseGeoJsonSubLevel()
if (! parseGeoJsonSubLevel(jsonObject.value(QStringLiteral("geometry")).toObject(),
geometryList, hasPoints))
{
return false;
}
// Create the placemark for this feature object with appropriate geometry
GeoDataPlacemark* placemark = new GeoDataPlacemark();
if (geometryList.length() < 1)
{
// No geometries available to add to the placemark
;
}
else if (geometryList.length() == 1)
{
// Single geometry
placemark->setGeometry(geometryList[0]);
}
else
{
// Multiple geometries require a GeoDataMultiGeometry class
GeoDataMultiGeometry* geom = new GeoDataMultiGeometry();
for (int i = 0; i < geometryList.length(); ++i)
{
geom->append(geometryList[i]);
}
placemark->setGeometry(geom);
}
// Create copies of the default styles
GeoDataStyle::Ptr style(new GeoDataStyle(*(placemark->style())));
GeoDataIconStyle iconStyle = hasPoints ? *m_iconStylePoints : *m_iconStyleOther;
GeoDataLineStyle lineStyle = *m_lineStyle;
GeoDataPolyStyle polyStyle = *m_polyStyle;
// Parse any associated properties
const QJsonObject propertiesObject = jsonObject.value(QStringLiteral("properties")).toObject();
QJsonObject::ConstIterator iter = propertiesObject.begin();
const QJsonObject::ConstIterator end = propertiesObject.end();
OsmPlacemarkData osmData;
for (; iter != end; ++iter)
{
// Pass the value through QVariant to also get booleans and numbers
const QString propertyValue = iter.value().toVariant().toString();
const QString propertyKey = iter.key();
if (iter.value().isObject() || iter.value().isArray())
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Skipping unsupported JSON property containing an object or array:" << propertyKey;
continue;
}
if (propertyKey == QStringLiteral("name"))
{
// The "name" property is not defined in the Simplestyle specification, but is used
// extensively in the wild. Treat "name" and "title" essentially the same for the
// purposes of placemarks (although osmData tags will preserve the distinction).
placemark->setName(propertyValue);
osmData.addTag(propertyKey, propertyValue);
}
else if (propertyKey == QStringLiteral("title"))
{
placemark->setName(propertyValue);
osmData.addTag(propertyKey, propertyValue);
}
else if (propertyKey == QStringLiteral("description"))
{
placemark->setDescription(propertyValue);
osmData.addTag(propertyKey, propertyValue);
}
else if (propertyKey == QStringLiteral("marker-size"))
{
// TODO: Implement marker-size handling
if (propertyValue == QStringLiteral(""))
{
// Use the default value
;
}
else
{
//qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring unimplemented marker-size property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("marker-symbol"))
{
// TODO: Implement marker-symbol handling
if (propertyValue == QStringLiteral(""))
{
// Use the default value
;
}
else
{
//qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring unimplemented marker-symbol property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("marker-color"))
{
// Even though the Simplestyle spec allows colors to omit the leading "#", this
// implementation assumes it is always present, as this then allows named colors
// understood by QColor as an extension
QColor color = QColor(propertyValue);
if (color.isValid())
{
iconStyle.setColor(color); // Currently ignored by Marble
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid marker-color property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("stroke"))
{
QColor color = QColor(propertyValue); // Assume leading "#" is present
if (color.isValid())
{
color.setAlpha(lineStyle.color().alpha());
lineStyle.setColor(color);
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid stroke property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("stroke-opacity"))
{
bool ok;
float opacity = propertyValue.toFloat(&ok);
if (ok && opacity >= 0.0 && opacity <= 1.0)
{
QColor color = lineStyle.color();
color.setAlphaF(opacity);
lineStyle.setColor(color);
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid stroke-opacity property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("stroke-width"))
{
bool ok;
float width = propertyValue.toFloat(&ok);
if (ok && width >= 0.0)
{
lineStyle.setWidth(width);
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid stroke-width property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("fill"))
{
QColor color = QColor(propertyValue); // Assume leading "#" is present
if (color.isValid())
{
color.setAlpha(polyStyle.color().alpha());
polyStyle.setColor(color);
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid fill property:" << propertyValue;
}
}
else if (propertyKey == QStringLiteral("fill-opacity"))
{
bool ok;
float opacity = propertyValue.toFloat(&ok);
if (ok && opacity >= 0.0 && opacity <= 1.0)
{
QColor color = polyStyle.color();
color.setAlphaF(opacity);
polyStyle.setColor(color);
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Ignoring invalid fill-opacity property:" << propertyValue;
}
}
else
{
// Property is not defined by the Simplestyle spec
osmData.addTag(propertyKey, propertyValue);
}
}
style->setIconStyle(iconStyle);
style->setLineStyle(lineStyle);
style->setPolyStyle(polyStyle);
style->setLabelStyle(*m_labelStyle);
placemark->setStyle(style);
placemark->setOsmData(osmData);
placemark->setVisible(true);
const GeoDataPlacemark::GeoDataVisualCategory category =
StyleBuilder::determineVisualCategory(osmData);
if (category != GeoDataPlacemark::None)
{
placemark->setVisualCategory(category);
}
m_document->append(placemark);
return true;
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Missing FeatureCollection or Feature object in GeoJSON file";
return false;
}
}
bool JsonParser::parseGeoJsonSubLevel(const QJsonObject& jsonObject,
QVector<GeoDataGeometry*>& geometryList, bool& hasPoints)
{
// The GeoJSON object type
const QString jsonObjectType = jsonObject.value(QStringLiteral("type")).toString();
if (jsonObjectType == QStringLiteral("FeatureCollection")
|| jsonObjectType == QStringLiteral("Feature"))
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Cannot have FeatureCollection or Feature objects at this level of the GeoJSON file";
return false;
}
else if (jsonObjectType == QStringLiteral("GeometryCollection"))
{
// Handle the GeometryCollection object, which may contain multiple geometry objects
const QJsonArray geometryArray = jsonObject.value(QStringLiteral("geometries")).toArray();
for (int geometryIndex = 0; geometryIndex < geometryArray.size(); ++geometryIndex)
{
if (! parseGeoJsonSubLevel(geometryArray[geometryIndex].toObject(), geometryList, hasPoints))
{
return false;
}
}
return true;
}
// Handle remaining GeoJSON objects, which each have a "coordinates" member (an array)
const QJsonArray coordinateArray = jsonObject.value(QStringLiteral("coordinates")).toArray();
if (jsonObjectType == QStringLiteral("Point"))
{
// A Point object has a single GeoJSON position: an array of at least two values
GeoDataPoint* geom = new GeoDataPoint();
const qreal lon = coordinateArray.at(0).toDouble();
const qreal lat = coordinateArray.at(1).toDouble();
const qreal alt = coordinateArray.at(2).toDouble(); // If missing, uses 0 as the default
geom->setCoordinates(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
geometryList.append(geom);
hasPoints = true;
return true;
}
else if (jsonObjectType == QStringLiteral("MultiPoint"))
{
// A MultiPoint object has an array of GeoJSON positions (ie, a two-level array)
for (int positionIndex = 0; positionIndex < coordinateArray.size(); ++positionIndex)
{
const QJsonArray positionArray = coordinateArray[positionIndex].toArray();
GeoDataPoint* geom = new GeoDataPoint();
const qreal lon = positionArray.at(0).toDouble();
const qreal lat = positionArray.at(1).toDouble();
const qreal alt = positionArray.at(2).toDouble();
geom->setCoordinates(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
geometryList.append(geom);
}
hasPoints = true;
return true;
}
else if (jsonObjectType == QStringLiteral("LineString"))
{
// A LineString object has an array of GeoJSON positions (ie, a two-level array)
GeoDataLineString* geom = new GeoDataLineString(RespectLatitudeCircle | Tessellate);
for (int positionIndex = 0; positionIndex < coordinateArray.size(); ++positionIndex)
{
const QJsonArray positionArray = coordinateArray[positionIndex].toArray();
const qreal lon = positionArray.at(0).toDouble();
const qreal lat = positionArray.at(1).toDouble();
const qreal alt = positionArray.at(2).toDouble();
geom->append(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
}
geometryList.append(geom);
return true;
}
else if (jsonObjectType == QStringLiteral("MultiLineString"))
{
// A MultiLineString object has an array of arrays of GeoJSON positions (three-level)
for (int lineStringIndex = 0; lineStringIndex < coordinateArray.size(); ++lineStringIndex)
{
const QJsonArray lineStringArray = coordinateArray[lineStringIndex].toArray();
GeoDataLineString* geom = new GeoDataLineString(RespectLatitudeCircle | Tessellate);
for (int positionIndex = 0; positionIndex < lineStringArray.size(); ++positionIndex)
{
const QJsonArray positionArray = lineStringArray[positionIndex].toArray();
const qreal lon = positionArray.at(0).toDouble();
const qreal lat = positionArray.at(1).toDouble();
const qreal alt = positionArray.at(2).toDouble();
geom->append(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
}
geometryList.append(geom);
}
return true;
}
else if (jsonObjectType == QStringLiteral("Polygon"))
{
// A Polygon object has an array of arrays of GeoJSON positions: the first array within the
// top-level Polygon coordinates array is the outer boundary, following arrays are inner
// holes (if any)
GeoDataPolygon* geom = new GeoDataPolygon(RespectLatitudeCircle | Tessellate);
for (int ringIndex = 0; ringIndex < coordinateArray.size(); ++ringIndex)
{
const QJsonArray ringArray = coordinateArray[ringIndex].toArray();
GeoDataLinearRing linearRing;
for (int positionIndex = 0; positionIndex < ringArray.size(); ++positionIndex)
{
const QJsonArray positionArray = ringArray[positionIndex].toArray();
const qreal lon = positionArray.at(0).toDouble();
const qreal lat = positionArray.at(1).toDouble();
const qreal alt = positionArray.at(2).toDouble();
linearRing.append(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
}
if (ringIndex == 0)
{
// Outer boundary of the polygon
geom->setOuterBoundary(linearRing);
}
else
{
geom->appendInnerBoundary(linearRing);
}
}
geometryList.append(geom);
return true;
}
else if (jsonObjectType == QStringLiteral("MultiPolygon"))
{
// A MultiPolygon object has an array of Polygon arrays (ie, a four-level array)
for (int polygonIndex = 0; polygonIndex < coordinateArray.size(); ++polygonIndex)
{
const QJsonArray polygonArray = coordinateArray[polygonIndex].toArray();
GeoDataPolygon* geom = new GeoDataPolygon(RespectLatitudeCircle | Tessellate);
for (int ringIndex = 0; ringIndex < polygonArray.size(); ++ringIndex)
{
const QJsonArray ringArray = polygonArray[ringIndex].toArray();
GeoDataLinearRing linearRing;
for (int positionIndex = 0; positionIndex < ringArray.size(); ++positionIndex)
{
const QJsonArray positionArray = ringArray[positionIndex].toArray();
const qreal lon = positionArray.at(0).toDouble();
const qreal lat = positionArray.at(1).toDouble();
const qreal alt = positionArray.at(2).toDouble();
linearRing.append(GeoDataCoordinates(lon, lat, alt, GeoDataCoordinates::Degree));
}
if (ringIndex == 0)
{
// Outer boundary of the polygon
geom->setOuterBoundary(linearRing);
}
else
{
geom->appendInnerBoundary(linearRing);
}
}
geometryList.append(geom);
}
return true;
}
else if (jsonObjectType == QStringLiteral(""))
{
// Unlocated Feature objects have a null value for "geometry" (RFC7946 section 3.2)
return true;
}
else
{
qCDebug(DIGIKAM_MARBLE_LOG) << "Unknown GeoJSON object type" << jsonObjectType;
return false;
}
}
} // namespace Marble
|