Coverage Report

Created: 2026-09-14 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/ogr/ogrgeojsonwriter.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  OpenGIS Simple Features Reference Implementation
4
 * Purpose:  Implementation of GeoJSON writer utilities (OGR GeoJSON Driver).
5
 * Author:   Mateusz Loskot, mateusz@loskot.net
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2007, Mateusz Loskot
9
 * Copyright (c) 2008-2014, Even Rouault <even dot rouault at spatialys.com>
10
 *
11
 * SPDX-License-Identifier: MIT
12
 ****************************************************************************/
13
14
/*! @cond Doxygen_Suppress */
15
16
#define JSON_C_VER_013 (13 << 8)
17
18
#include "ogrgeojsonwriter.h"
19
#include "ogr_geometry.h"
20
#include "ogrgeojsongeometry.h"
21
#include "ogrlibjsonutils.h"
22
#include "ogr_feature.h"
23
#include "ogr_p.h"
24
#include <json.h>  // JSON-C
25
26
#if (!defined(JSON_C_VERSION_NUM)) || (JSON_C_VERSION_NUM < JSON_C_VER_013)
27
#include <json_object_private.h>
28
#endif
29
30
#include <printbuf.h>
31
#include "ogr_api.h"
32
33
#include <algorithm>
34
#include <cmath>
35
#include <cstdint>
36
#include <limits>
37
#include <optional>
38
39
static json_object *
40
json_object_new_float_with_significant_figures(float fVal,
41
                                               int nSignificantFigures);
42
43
static json_object *
44
OGRGeoJSONWritePoint(const OGRPoint *poPoint,
45
                     const OGRGeoJSONWriteOptions &oOptions);
46
47
static json_object *
48
OGRGeoJSONWriteSimpleCurve(const OGRSimpleCurve *poLine,
49
                           const OGRGeoJSONWriteOptions &oOptions);
50
51
static json_object *
52
OGRGeoJSONWriteMultiPoint(const OGRMultiPoint *poGeometry,
53
                          const OGRGeoJSONWriteOptions &oOptions);
54
55
static json_object *
56
OGRGeoJSONWriteMultiLineString(const OGRMultiLineString *poGeometry,
57
                               const OGRGeoJSONWriteOptions &oOptions);
58
59
static json_object *
60
OGRGeoJSONWriteMultiPolygon(const OGRMultiPolygon *poGeometry,
61
                            const OGRGeoJSONWriteOptions &oOptions);
62
63
static json_object *
64
OGRGeoJSONWriteGeometryCollection(const OGRGeometryCollection *poGeometry,
65
                                  const OGRGeoJSONWriteOptions &oOptions);
66
67
static json_object *
68
OGRGeoJSONWriteCoords(double dfX, double dfY, std::optional<double> dfZ,
69
                      std::optional<double> dfM,
70
                      const OGRGeoJSONWriteOptions &oOptions);
71
72
static json_object *
73
OGRGeoJSONWriteLineCoords(const OGRSimpleCurve *poLine,
74
                          const OGRGeoJSONWriteOptions &oOptions);
75
76
static json_object *
77
OGRGeoJSONWriteRingCoords(const OGRLinearRing *poLine, bool bIsExteriorRing,
78
                          const OGRGeoJSONWriteOptions &oOptions);
79
80
static json_object *
81
OGRGeoJSONWriteCompoundCurve(const OGRCompoundCurve *poCC,
82
                             const OGRGeoJSONWriteOptions &oOptions);
83
84
static json_object *
85
OGRGeoJSONWriteCurvePolygon(const OGRCurvePolygon *poCP,
86
                            const OGRGeoJSONWriteOptions &oOptions);
87
88
/************************************************************************/
89
/*                         SetRFC7946Settings()                         */
90
/************************************************************************/
91
92
/*! @cond Doxygen_Suppress */
93
void OGRGeoJSONWriteOptions::SetRFC7946Settings()
94
0
{
95
0
    bBBOXRFC7946 = true;
96
0
    if (nXYCoordPrecision < 0)
97
0
        nXYCoordPrecision = 7;
98
0
    if (nZCoordPrecision < 0)
99
0
        nZCoordPrecision = 3;
100
0
    bPolygonRightHandRule = true;
101
0
    bCanPatchCoordinatesWithNativeData = false;
102
0
    bHonourReservedRFC7946Members = true;
103
0
}
104
105
void OGRGeoJSONWriteOptions::SetIDOptions(CSLConstList papszOptions)
106
0
{
107
108
0
    osIDField = CSLFetchNameValueDef(papszOptions, "ID_FIELD", "");
109
0
    const char *pszIDFieldType = CSLFetchNameValue(papszOptions, "ID_TYPE");
110
0
    if (pszIDFieldType)
111
0
    {
112
0
        if (EQUAL(pszIDFieldType, "String"))
113
0
        {
114
0
            bForceIDFieldType = true;
115
0
            eForcedIDFieldType = OFTString;
116
0
        }
117
0
        else if (EQUAL(pszIDFieldType, "Integer"))
118
0
        {
119
0
            bForceIDFieldType = true;
120
0
            eForcedIDFieldType = OFTInteger64;
121
0
        }
122
0
    }
123
0
    bGenerateID =
124
0
        CPL_TO_BOOL(CSLFetchBoolean(papszOptions, "ID_GENERATE", false));
125
0
}
126
127
/*! @endcond */
128
129
/************************************************************************/
130
/*                       json_object_new_coord()                        */
131
/************************************************************************/
132
133
static json_object *
134
json_object_new_coord(double dfVal, int nDimIdx,
135
                      const OGRGeoJSONWriteOptions &oOptions)
136
0
{
137
    // If coordinate precision is specified, or significant figures is not
138
    // then use the '%f' formatting.
139
0
    if (nDimIdx <= 2)
140
0
    {
141
0
        if (oOptions.nXYCoordPrecision >= 0 || oOptions.nSignificantFigures < 0)
142
0
            return json_object_new_double_with_precision(
143
0
                dfVal, oOptions.nXYCoordPrecision);
144
0
    }
145
0
    else
146
0
    {
147
0
        if (oOptions.nZCoordPrecision >= 0 || oOptions.nSignificantFigures < 0)
148
0
            return json_object_new_double_with_precision(
149
0
                dfVal, oOptions.nZCoordPrecision);
150
0
    }
151
152
0
    return json_object_new_double_with_significant_figures(
153
0
        dfVal, oOptions.nSignificantFigures);
154
0
}
155
156
/************************************************************************/
157
/*                   OGRGeoJSONIsPatchablePosition()                    */
158
/************************************************************************/
159
160
static bool OGRGeoJSONIsPatchablePosition(json_object *poJSonCoordinates,
161
                                          json_object *poNativeCoordinates)
162
0
{
163
0
    return json_object_get_type(poJSonCoordinates) == json_type_array &&
164
0
           json_object_get_type(poNativeCoordinates) == json_type_array &&
165
0
           json_object_array_length(poJSonCoordinates) == 3 &&
166
0
           json_object_array_length(poNativeCoordinates) >= 4 &&
167
0
           json_object_get_type(json_object_array_get_idx(
168
0
               poJSonCoordinates, 0)) != json_type_array &&
169
0
           json_object_get_type(json_object_array_get_idx(
170
0
               poNativeCoordinates, 0)) != json_type_array;
171
0
}
172
173
/************************************************************************/
174
/*                   OGRGeoJSONIsCompatiblePosition()                   */
175
/************************************************************************/
176
177
static bool OGRGeoJSONIsCompatiblePosition(json_object *poJSonCoordinates,
178
                                           json_object *poNativeCoordinates)
179
0
{
180
0
    return json_object_get_type(poJSonCoordinates) == json_type_array &&
181
0
           json_object_get_type(poNativeCoordinates) == json_type_array &&
182
0
           json_object_array_length(poJSonCoordinates) ==
183
0
               json_object_array_length(poNativeCoordinates) &&
184
0
           json_object_get_type(json_object_array_get_idx(
185
0
               poJSonCoordinates, 0)) != json_type_array &&
186
0
           json_object_get_type(json_object_array_get_idx(
187
0
               poNativeCoordinates, 0)) != json_type_array;
188
0
}
189
190
/************************************************************************/
191
/*                      OGRGeoJSONPatchPosition()                       */
192
/************************************************************************/
193
194
static void OGRGeoJSONPatchPosition(json_object *poJSonCoordinates,
195
                                    json_object *poNativeCoordinates)
196
0
{
197
0
    const auto nLength = json_object_array_length(poNativeCoordinates);
198
0
    for (auto i = decltype(nLength){3}; i < nLength; i++)
199
0
    {
200
0
        json_object_array_add(
201
0
            poJSonCoordinates,
202
0
            json_object_get(json_object_array_get_idx(poNativeCoordinates, i)));
203
0
    }
204
0
}
205
206
/************************************************************************/
207
/*                     OGRGeoJSONIsPatchableArray()                     */
208
/************************************************************************/
209
210
static bool OGRGeoJSONIsPatchableArray(json_object *poJSonArray,
211
                                       json_object *poNativeArray, int nDepth)
212
0
{
213
0
    if (nDepth == 0)
214
0
        return OGRGeoJSONIsPatchablePosition(poJSonArray, poNativeArray);
215
216
0
    if (json_object_get_type(poJSonArray) == json_type_array &&
217
0
        json_object_get_type(poNativeArray) == json_type_array)
218
0
    {
219
0
        const auto nLength = json_object_array_length(poJSonArray);
220
0
        if (nLength == json_object_array_length(poNativeArray))
221
0
        {
222
0
            if (nLength > 0)
223
0
            {
224
0
                json_object *poJSonChild =
225
0
                    json_object_array_get_idx(poJSonArray, 0);
226
0
                json_object *poNativeChild =
227
0
                    json_object_array_get_idx(poNativeArray, 0);
228
0
                if (!OGRGeoJSONIsPatchableArray(poJSonChild, poNativeChild,
229
0
                                                nDepth - 1))
230
0
                {
231
0
                    return false;
232
0
                }
233
                // Light check as a former extensive check was done in
234
                // OGRGeoJSONComputePatchableOrCompatibleArray
235
0
            }
236
0
            return true;
237
0
        }
238
0
    }
239
0
    return false;
240
0
}
241
242
/************************************************************************/
243
/*            OGRGeoJSONComputePatchableOrCompatibleArray()             */
244
/************************************************************************/
245
246
/* Returns true if the objects are comparable, ie Point vs Point, LineString
247
   vs LineString, but they might not be patchable or compatible */
248
static bool OGRGeoJSONComputePatchableOrCompatibleArrayInternal(
249
    json_object *poJSonArray, json_object *poNativeArray, int nDepth,
250
    bool &bOutPatchable, bool &bOutCompatible)
251
0
{
252
0
    if (nDepth == 0)
253
0
    {
254
0
        bOutPatchable &=
255
0
            OGRGeoJSONIsPatchablePosition(poJSonArray, poNativeArray);
256
0
        bOutCompatible &=
257
0
            OGRGeoJSONIsCompatiblePosition(poJSonArray, poNativeArray);
258
0
        return json_object_get_type(poJSonArray) == json_type_array &&
259
0
               json_object_get_type(poNativeArray) == json_type_array &&
260
0
               json_object_get_type(json_object_array_get_idx(
261
0
                   poJSonArray, 0)) != json_type_array &&
262
0
               json_object_get_type(json_object_array_get_idx(
263
0
                   poNativeArray, 0)) != json_type_array;
264
0
    }
265
266
0
    if (json_object_get_type(poJSonArray) == json_type_array &&
267
0
        json_object_get_type(poNativeArray) == json_type_array)
268
0
    {
269
0
        const auto nLength = json_object_array_length(poJSonArray);
270
0
        if (nLength == json_object_array_length(poNativeArray))
271
0
        {
272
0
            for (auto i = decltype(nLength){0}; i < nLength; i++)
273
0
            {
274
0
                json_object *poJSonChild =
275
0
                    json_object_array_get_idx(poJSonArray, i);
276
0
                json_object *poNativeChild =
277
0
                    json_object_array_get_idx(poNativeArray, i);
278
0
                if (!OGRGeoJSONComputePatchableOrCompatibleArrayInternal(
279
0
                        poJSonChild, poNativeChild, nDepth - 1, bOutPatchable,
280
0
                        bOutCompatible))
281
0
                {
282
0
                    return false;
283
0
                }
284
0
                if (!bOutPatchable && !bOutCompatible)
285
0
                    break;
286
0
            }
287
0
            return true;
288
0
        }
289
0
    }
290
291
0
    bOutPatchable = false;
292
0
    bOutCompatible = false;
293
0
    return false;
294
0
}
295
296
/* Returns true if the objects are comparable, ie Point vs Point, LineString
297
   vs LineString, but they might not be patchable or compatible */
298
static bool OGRGeoJSONComputePatchableOrCompatibleArray(
299
    json_object *poJSonArray, json_object *poNativeArray, int nDepth,
300
    bool &bOutPatchable, bool &bOutCompatible)
301
0
{
302
0
    bOutPatchable = true;
303
0
    bOutCompatible = true;
304
0
    return OGRGeoJSONComputePatchableOrCompatibleArrayInternal(
305
0
        poJSonArray, poNativeArray, nDepth, bOutPatchable, bOutCompatible);
306
0
}
307
308
/************************************************************************/
309
/*                        OGRGeoJSONPatchArray()                        */
310
/************************************************************************/
311
312
static void OGRGeoJSONPatchArray(json_object *poJSonArray,
313
                                 json_object *poNativeArray, int nDepth)
314
0
{
315
0
    if (nDepth == 0)
316
0
    {
317
0
        OGRGeoJSONPatchPosition(poJSonArray, poNativeArray);
318
0
        return;
319
0
    }
320
0
    const auto nLength = json_object_array_length(poJSonArray);
321
0
    for (auto i = decltype(nLength){0}; i < nLength; i++)
322
0
    {
323
0
        json_object *poJSonChild = json_object_array_get_idx(poJSonArray, i);
324
0
        json_object *poNativeChild =
325
0
            json_object_array_get_idx(poNativeArray, i);
326
0
        OGRGeoJSONPatchArray(poJSonChild, poNativeChild, nDepth - 1);
327
0
    }
328
0
}
329
330
/************************************************************************/
331
/*                   OGRGeoJSONIsPatchableGeometry()                    */
332
/************************************************************************/
333
334
static bool OGRGeoJSONIsPatchableGeometry(json_object *poJSonGeometry,
335
                                          json_object *poNativeGeometry,
336
                                          bool &bOutPatchableCoords,
337
                                          bool &bOutCompatibleCoords)
338
0
{
339
0
    if (json_object_get_type(poJSonGeometry) != json_type_object ||
340
0
        json_object_get_type(poNativeGeometry) != json_type_object)
341
0
    {
342
0
        return false;
343
0
    }
344
345
0
    json_object *poType = CPL_json_object_object_get(poJSonGeometry, "type");
346
0
    json_object *poNativeType =
347
0
        CPL_json_object_object_get(poNativeGeometry, "type");
348
0
    if (poType == nullptr || poNativeType == nullptr ||
349
0
        json_object_get_type(poType) != json_type_string ||
350
0
        json_object_get_type(poNativeType) != json_type_string ||
351
0
        strcmp(json_object_get_string(poType),
352
0
               json_object_get_string(poNativeType)) != 0)
353
0
    {
354
0
        return false;
355
0
    }
356
357
0
    json_object_iter it;
358
0
    it.key = nullptr;
359
0
    it.val = nullptr;
360
0
    it.entry = nullptr;
361
0
    json_object_object_foreachC(poNativeGeometry, it)
362
0
    {
363
0
        if (strcmp(it.key, "coordinates") == 0)
364
0
        {
365
0
            json_object *poJSonCoordinates =
366
0
                CPL_json_object_object_get(poJSonGeometry, "coordinates");
367
0
            json_object *poNativeCoordinates = it.val;
368
            // 0 = Point
369
            // 1 = LineString or MultiPoint
370
            // 2 = MultiLineString or Polygon
371
            // 3 = MultiPolygon
372
0
            for (int i = 0; i <= 3; i++)
373
0
            {
374
0
                if (OGRGeoJSONComputePatchableOrCompatibleArray(
375
0
                        poJSonCoordinates, poNativeCoordinates, i,
376
0
                        bOutPatchableCoords, bOutCompatibleCoords))
377
0
                {
378
0
                    return bOutPatchableCoords || bOutCompatibleCoords;
379
0
                }
380
0
            }
381
0
            return false;
382
0
        }
383
0
        if (strcmp(it.key, "geometries") == 0)
384
0
        {
385
0
            json_object *poJSonGeometries =
386
0
                CPL_json_object_object_get(poJSonGeometry, "geometries");
387
0
            json_object *poNativeGeometries = it.val;
388
0
            if (json_object_get_type(poJSonGeometries) == json_type_array &&
389
0
                json_object_get_type(poNativeGeometries) == json_type_array)
390
0
            {
391
0
                const auto nLength = json_object_array_length(poJSonGeometries);
392
0
                if (nLength == json_object_array_length(poNativeGeometries))
393
0
                {
394
0
                    for (auto i = decltype(nLength){0}; i < nLength; i++)
395
0
                    {
396
0
                        json_object *poJSonChild =
397
0
                            json_object_array_get_idx(poJSonGeometries, i);
398
0
                        json_object *poNativeChild =
399
0
                            json_object_array_get_idx(poNativeGeometries, i);
400
0
                        if (!OGRGeoJSONIsPatchableGeometry(
401
0
                                poJSonChild, poNativeChild, bOutPatchableCoords,
402
0
                                bOutCompatibleCoords))
403
0
                        {
404
0
                            return false;
405
0
                        }
406
0
                    }
407
0
                    return true;
408
0
                }
409
0
            }
410
0
            return false;
411
0
        }
412
0
    }
413
0
    return false;
414
0
}
415
416
/************************************************************************/
417
/*                      OGRGeoJSONPatchGeometry()                       */
418
/************************************************************************/
419
420
static void OGRGeoJSONPatchGeometry(json_object *poJSonGeometry,
421
                                    json_object *poNativeGeometry,
422
                                    bool bPatchableCoordinates,
423
                                    const OGRGeoJSONWriteOptions &oOptions)
424
0
{
425
0
    json_object_iter it;
426
0
    it.key = nullptr;
427
0
    it.val = nullptr;
428
0
    it.entry = nullptr;
429
0
    json_object_object_foreachC(poNativeGeometry, it)
430
0
    {
431
0
        if (strcmp(it.key, "type") == 0 || strcmp(it.key, "bbox") == 0)
432
0
        {
433
0
            continue;
434
0
        }
435
0
        if (strcmp(it.key, "coordinates") == 0)
436
0
        {
437
0
            if (!bPatchableCoordinates &&
438
0
                !oOptions.bCanPatchCoordinatesWithNativeData)
439
0
            {
440
0
                continue;
441
0
            }
442
443
0
            json_object *poJSonCoordinates =
444
0
                CPL_json_object_object_get(poJSonGeometry, "coordinates");
445
0
            json_object *poNativeCoordinates = it.val;
446
0
            for (int i = 0; i <= 3; i++)
447
0
            {
448
0
                if (OGRGeoJSONIsPatchableArray(poJSonCoordinates,
449
0
                                               poNativeCoordinates, i))
450
0
                {
451
0
                    OGRGeoJSONPatchArray(poJSonCoordinates, poNativeCoordinates,
452
0
                                         i);
453
0
                    break;
454
0
                }
455
0
            }
456
457
0
            continue;
458
0
        }
459
0
        if (strcmp(it.key, "geometries") == 0)
460
0
        {
461
0
            json_object *poJSonGeometries =
462
0
                CPL_json_object_object_get(poJSonGeometry, "geometries");
463
0
            json_object *poNativeGeometries = it.val;
464
0
            const auto nLength = json_object_array_length(poJSonGeometries);
465
0
            for (auto i = decltype(nLength){0}; i < nLength; i++)
466
0
            {
467
0
                json_object *poJSonChild =
468
0
                    json_object_array_get_idx(poJSonGeometries, i);
469
0
                json_object *poNativeChild =
470
0
                    json_object_array_get_idx(poNativeGeometries, i);
471
0
                OGRGeoJSONPatchGeometry(poJSonChild, poNativeChild,
472
0
                                        bPatchableCoordinates, oOptions);
473
0
            }
474
475
0
            continue;
476
0
        }
477
478
        // See https://tools.ietf.org/html/rfc7946#section-7.1
479
0
        if (oOptions.bHonourReservedRFC7946Members &&
480
0
            (strcmp(it.key, "geometry") == 0 ||
481
0
             strcmp(it.key, "properties") == 0 ||
482
0
             strcmp(it.key, "features") == 0))
483
0
        {
484
0
            continue;
485
0
        }
486
487
0
        json_object_object_add(poJSonGeometry, it.key, json_object_get(it.val));
488
0
    }
489
0
}
490
491
/************************************************************************/
492
/*                          OGRGeoJSONGetBBox                           */
493
/************************************************************************/
494
495
OGREnvelope3D OGRGeoJSONGetBBox(const OGRGeometry *poGeometry,
496
                                const OGRGeoJSONWriteOptions &oOptions)
497
0
{
498
0
    OGREnvelope3D sEnvelope;
499
0
    poGeometry->getEnvelope(&sEnvelope);
500
501
0
    if (oOptions.bBBOXRFC7946)
502
0
    {
503
        // Heuristics to determine if the geometry was split along the
504
        // date line.
505
0
        const double EPS = 1e-7;
506
0
        const OGRwkbGeometryType eType =
507
0
            wkbFlatten(poGeometry->getGeometryType());
508
0
        const bool bMultiPart =
509
0
            OGR_GT_IsSubClassOf(eType, wkbGeometryCollection) &&
510
0
            poGeometry->toGeometryCollection()->getNumGeometries() >= 2;
511
0
        if (bMultiPart && fabs(sEnvelope.MinX - (-180.0)) < EPS &&
512
0
            fabs(sEnvelope.MaxX - 180.0) < EPS)
513
0
        {
514
            // First heuristics (quite safe) when the geometry looks to
515
            // have been really split at the dateline.
516
0
            const auto *poGC = poGeometry->toGeometryCollection();
517
0
            double dfWestLimit = -180.0;
518
0
            double dfEastLimit = 180.0;
519
0
            bool bWestLimitIsInit = false;
520
0
            bool bEastLimitIsInit = false;
521
0
            for (const auto *poMember : poGC)
522
0
            {
523
0
                OGREnvelope sEnvelopePart;
524
0
                if (poMember->IsEmpty())
525
0
                    continue;
526
0
                poMember->getEnvelope(&sEnvelopePart);
527
0
                const bool bTouchesMinus180 =
528
0
                    fabs(sEnvelopePart.MinX - (-180.0)) < EPS;
529
0
                const bool bTouchesPlus180 =
530
0
                    fabs(sEnvelopePart.MaxX - 180.0) < EPS;
531
0
                if (bTouchesMinus180 && !bTouchesPlus180)
532
0
                {
533
0
                    if (sEnvelopePart.MaxX > dfEastLimit || !bEastLimitIsInit)
534
0
                    {
535
0
                        bEastLimitIsInit = true;
536
0
                        dfEastLimit = sEnvelopePart.MaxX;
537
0
                    }
538
0
                }
539
0
                else if (bTouchesPlus180 && !bTouchesMinus180)
540
0
                {
541
0
                    if (sEnvelopePart.MinX < dfWestLimit || !bWestLimitIsInit)
542
0
                    {
543
0
                        bWestLimitIsInit = true;
544
0
                        dfWestLimit = sEnvelopePart.MinX;
545
0
                    }
546
0
                }
547
0
                else if (!bTouchesMinus180 && !bTouchesPlus180)
548
0
                {
549
0
                    if (sEnvelopePart.MinX > 0 &&
550
0
                        (sEnvelopePart.MinX < dfWestLimit || !bWestLimitIsInit))
551
0
                    {
552
0
                        bWestLimitIsInit = true;
553
0
                        dfWestLimit = sEnvelopePart.MinX;
554
0
                    }
555
0
                    else if (sEnvelopePart.MaxX < 0 &&
556
0
                             (sEnvelopePart.MaxX > dfEastLimit ||
557
0
                              !bEastLimitIsInit))
558
0
                    {
559
0
                        bEastLimitIsInit = true;
560
0
                        dfEastLimit = sEnvelopePart.MaxX;
561
0
                    }
562
0
                }
563
0
            }
564
0
            sEnvelope.MinX = dfWestLimit;
565
0
            sEnvelope.MaxX = dfEastLimit;
566
0
        }
567
0
        else if (bMultiPart && sEnvelope.MaxX - sEnvelope.MinX > 180 &&
568
0
                 sEnvelope.MinX >= -180 && sEnvelope.MaxX <= 180)
569
0
        {
570
            // More fragile heuristics for a geometry like Alaska
571
            // (https://github.com/qgis/QGIS/issues/42827) which spans over
572
            // the antimeridian but does not touch it.
573
0
            const auto *poGC = poGeometry->toGeometryCollection();
574
0
            double dfWestLimit = std::numeric_limits<double>::infinity();
575
0
            double dfEastLimit = -std::numeric_limits<double>::infinity();
576
0
            for (const auto *poMember : poGC)
577
0
            {
578
0
                OGREnvelope sEnvelopePart;
579
0
                if (poMember->IsEmpty())
580
0
                    continue;
581
0
                poMember->getEnvelope(&sEnvelopePart);
582
0
                if (sEnvelopePart.MinX > -120 && sEnvelopePart.MaxX < 120)
583
0
                {
584
0
                    dfWestLimit = std::numeric_limits<double>::infinity();
585
0
                    dfEastLimit = -std::numeric_limits<double>::infinity();
586
0
                    break;
587
0
                }
588
0
                if (sEnvelopePart.MinX > 0)
589
0
                {
590
0
                    dfWestLimit = std::min(dfWestLimit, sEnvelopePart.MinX);
591
0
                }
592
0
                else
593
0
                {
594
0
                    CPLAssert(sEnvelopePart.MaxX < 0);
595
0
                    dfEastLimit = std::max(dfEastLimit, sEnvelopePart.MaxX);
596
0
                }
597
0
            }
598
0
            if (dfWestLimit != std::numeric_limits<double>::infinity() &&
599
0
                dfEastLimit + 360 - dfWestLimit < 180)
600
0
            {
601
0
                sEnvelope.MinX = dfWestLimit;
602
0
                sEnvelope.MaxX = dfEastLimit;
603
0
            }
604
0
        }
605
0
    }
606
607
0
    return sEnvelope;
608
0
}
609
610
/************************************************************************/
611
/*                        OGRGeoJSONWriteFeature                        */
612
/************************************************************************/
613
614
json_object *OGRGeoJSONWriteFeature(OGRFeature *poFeature,
615
                                    const OGRGeoJSONWriteOptions &oOptions)
616
0
{
617
0
    CPLAssert(nullptr != poFeature);
618
619
0
    bool bWriteBBOX = oOptions.bWriteBBOX;
620
621
0
    json_object *poObj = json_object_new_object();
622
0
    CPLAssert(nullptr != poObj);
623
624
0
    json_object_object_add(poObj, "type", json_object_new_string("Feature"));
625
626
    /* -------------------------------------------------------------------- */
627
    /*      Write native JSon data.                                         */
628
    /* -------------------------------------------------------------------- */
629
0
    bool bIdAlreadyWritten = false;
630
0
    const char *pszNativeMediaType = poFeature->GetNativeMediaType();
631
0
    json_object *poNativeGeom = nullptr;
632
0
    bool bHasProperties = true;
633
0
    bool bWriteIdIfFoundInAttributes = true;
634
0
    if (pszNativeMediaType && OGRIsGeoJSONMediaType(pszNativeMediaType))
635
0
    {
636
0
        const char *pszNativeData = poFeature->GetNativeData();
637
0
        json_object *poNativeJSon = nullptr;
638
0
        if (pszNativeData && OGRJSonParse(pszNativeData, &poNativeJSon) &&
639
0
            json_object_get_type(poNativeJSon) == json_type_object)
640
0
        {
641
0
            json_object_iter it;
642
0
            it.key = nullptr;
643
0
            it.val = nullptr;
644
0
            it.entry = nullptr;
645
0
            bHasProperties = false;
646
0
            json_object_object_foreachC(poNativeJSon, it)
647
0
            {
648
0
                if (strcmp(it.key, "type") == 0)
649
0
                {
650
0
                    continue;
651
0
                }
652
0
                if (strcmp(it.key, "properties") == 0)
653
0
                {
654
0
                    bHasProperties = true;
655
0
                    continue;
656
0
                }
657
0
                if (strcmp(it.key, "bbox") == 0)
658
0
                {
659
0
                    bWriteBBOX = true;
660
0
                    continue;
661
0
                }
662
0
                if (strcmp(it.key, "geometry") == 0)
663
0
                {
664
0
                    poNativeGeom = json_object_get(it.val);
665
0
                    continue;
666
0
                }
667
0
                if (strcmp(it.key, "id") == 0)
668
0
                {
669
0
                    const auto eType = json_object_get_type(it.val);
670
                    // See https://tools.ietf.org/html/rfc7946#section-3.2
671
0
                    if (oOptions.bHonourReservedRFC7946Members &&
672
0
                        !oOptions.bForceIDFieldType &&
673
0
                        eType != json_type_string && eType != json_type_int &&
674
0
                        eType != json_type_double)
675
0
                    {
676
0
                        continue;
677
0
                    }
678
679
0
                    bIdAlreadyWritten = true;
680
681
0
                    if (it.val && oOptions.bForceIDFieldType &&
682
0
                        oOptions.eForcedIDFieldType == OFTInteger64)
683
0
                    {
684
0
                        if (eType != json_type_int)
685
0
                        {
686
0
                            json_object_object_add(
687
0
                                poObj, it.key,
688
0
                                json_object_new_int64(CPLAtoGIntBig(
689
0
                                    json_object_get_string(it.val))));
690
0
                            bWriteIdIfFoundInAttributes = false;
691
0
                            continue;
692
0
                        }
693
0
                    }
694
0
                    else if (it.val && oOptions.bForceIDFieldType &&
695
0
                             oOptions.eForcedIDFieldType == OFTString)
696
0
                    {
697
0
                        if (eType != json_type_string)
698
0
                        {
699
0
                            json_object_object_add(
700
0
                                poObj, it.key,
701
0
                                json_object_new_string(
702
0
                                    json_object_get_string(it.val)));
703
0
                            bWriteIdIfFoundInAttributes = false;
704
0
                            continue;
705
0
                        }
706
0
                    }
707
708
0
                    if (it.val != nullptr)
709
0
                    {
710
0
                        int nIdx =
711
0
                            poFeature->GetDefnRef()->GetFieldIndexCaseSensitive(
712
0
                                "id");
713
0
                        if (eType == json_type_string && nIdx >= 0 &&
714
0
                            poFeature->GetFieldDefnRef(nIdx)->GetType() ==
715
0
                                OFTString &&
716
0
                            strcmp(json_object_get_string(it.val),
717
0
                                   poFeature->GetFieldAsString(nIdx)) == 0)
718
0
                        {
719
0
                            bWriteIdIfFoundInAttributes = false;
720
0
                        }
721
0
                        else if (eType == json_type_int && nIdx >= 0 &&
722
0
                                 (poFeature->GetFieldDefnRef(nIdx)->GetType() ==
723
0
                                      OFTInteger ||
724
0
                                  poFeature->GetFieldDefnRef(nIdx)->GetType() ==
725
0
                                      OFTInteger64) &&
726
0
                                 json_object_get_int64(it.val) ==
727
0
                                     poFeature->GetFieldAsInteger64(nIdx))
728
0
                        {
729
0
                            bWriteIdIfFoundInAttributes = false;
730
0
                        }
731
0
                    }
732
0
                }
733
734
                // See https://tools.ietf.org/html/rfc7946#section-7.1
735
0
                if (oOptions.bHonourReservedRFC7946Members &&
736
0
                    (strcmp(it.key, "coordinates") == 0 ||
737
0
                     strcmp(it.key, "geometries") == 0 ||
738
0
                     strcmp(it.key, "features") == 0))
739
0
                {
740
0
                    continue;
741
0
                }
742
743
0
                json_object_object_add(poObj, it.key, json_object_get(it.val));
744
0
            }
745
0
            json_object_put(poNativeJSon);
746
0
        }
747
0
    }
748
749
    /* -------------------------------------------------------------------- */
750
    /*      Write FID if available                                          */
751
    /* -------------------------------------------------------------------- */
752
0
    OGRGeoJSONWriteId(poFeature, poObj, bIdAlreadyWritten, oOptions);
753
754
    /* -------------------------------------------------------------------- */
755
    /*      Write feature attributes to GeoJSON "properties" object.        */
756
    /* -------------------------------------------------------------------- */
757
0
    if (bHasProperties)
758
0
    {
759
0
        json_object *poObjProps = OGRGeoJSONWriteAttributes(
760
0
            poFeature, bWriteIdIfFoundInAttributes, oOptions);
761
0
        json_object_object_add(poObj, "properties", poObjProps);
762
0
    }
763
764
    /* -------------------------------------------------------------------- */
765
    /*      Write feature geometry to GeoJSON "geometry" object.            */
766
    /*      Null geometries are allowed, according to the GeoJSON Spec.     */
767
    /* -------------------------------------------------------------------- */
768
0
    json_object *poObjGeom = nullptr;
769
770
0
    OGRGeometry *poGeometry = poFeature->GetGeometryRef();
771
0
    if (nullptr != poGeometry)
772
0
    {
773
0
        poObjGeom = OGRGeoJSONWriteGeometry(poGeometry, oOptions);
774
775
0
        if (bWriteBBOX && !poGeometry->IsEmpty())
776
0
        {
777
0
            OGREnvelope3D sEnvelope = OGRGeoJSONGetBBox(poGeometry, oOptions);
778
779
0
            json_object *poObjBBOX = json_object_new_array();
780
0
            json_object_array_add(
781
0
                poObjBBOX, json_object_new_coord(sEnvelope.MinX, 1, oOptions));
782
0
            json_object_array_add(
783
0
                poObjBBOX, json_object_new_coord(sEnvelope.MinY, 2, oOptions));
784
0
            if (wkbHasZ(poGeometry->getGeometryType()))
785
0
                json_object_array_add(
786
0
                    poObjBBOX,
787
0
                    json_object_new_coord(sEnvelope.MinZ, 3, oOptions));
788
0
            json_object_array_add(
789
0
                poObjBBOX, json_object_new_coord(sEnvelope.MaxX, 1, oOptions));
790
0
            json_object_array_add(
791
0
                poObjBBOX, json_object_new_coord(sEnvelope.MaxY, 2, oOptions));
792
0
            if (wkbHasZ(poGeometry->getGeometryType()))
793
0
                json_object_array_add(
794
0
                    poObjBBOX,
795
0
                    json_object_new_coord(sEnvelope.MaxZ, 3, oOptions));
796
797
0
            json_object_object_add(poObj, "bbox", poObjBBOX);
798
0
        }
799
800
0
        bool bOutPatchableCoords = false;
801
0
        bool bOutCompatibleCoords = false;
802
0
        if (OGRGeoJSONIsPatchableGeometry(poObjGeom, poNativeGeom,
803
0
                                          bOutPatchableCoords,
804
0
                                          bOutCompatibleCoords))
805
0
        {
806
0
            OGRGeoJSONPatchGeometry(poObjGeom, poNativeGeom,
807
0
                                    bOutPatchableCoords, oOptions);
808
0
        }
809
0
    }
810
811
0
    json_object_object_add(poObj, "geometry", poObjGeom);
812
813
0
    if (poNativeGeom != nullptr)
814
0
        json_object_put(poNativeGeom);
815
816
0
    return poObj;
817
0
}
818
819
/************************************************************************/
820
/*                          OGRGeoJSONWriteId                           */
821
/************************************************************************/
822
823
void OGRGeoJSONWriteId(const OGRFeature *poFeature, json_object *poObj,
824
                       bool bIdAlreadyWritten,
825
                       const OGRGeoJSONWriteOptions &oOptions)
826
0
{
827
0
    if (!oOptions.osIDField.empty())
828
0
    {
829
0
        int nIdx = poFeature->GetDefnRef()->GetFieldIndexCaseSensitive(
830
0
            oOptions.osIDField);
831
0
        if (nIdx >= 0)
832
0
        {
833
0
            if ((oOptions.bForceIDFieldType &&
834
0
                 oOptions.eForcedIDFieldType == OFTInteger64) ||
835
0
                (!oOptions.bForceIDFieldType &&
836
0
                 (poFeature->GetFieldDefnRef(nIdx)->GetType() == OFTInteger ||
837
0
                  poFeature->GetFieldDefnRef(nIdx)->GetType() == OFTInteger64)))
838
0
            {
839
0
                json_object_object_add(
840
0
                    poObj, "id",
841
0
                    json_object_new_int64(
842
0
                        poFeature->GetFieldAsInteger64(nIdx)));
843
0
            }
844
0
            else
845
0
            {
846
0
                json_object_object_add(
847
0
                    poObj, "id",
848
0
                    json_object_new_string(poFeature->GetFieldAsString(nIdx)));
849
0
            }
850
0
        }
851
0
    }
852
0
    else if (poFeature->GetFID() != OGRNullFID && !bIdAlreadyWritten)
853
0
    {
854
0
        if (oOptions.bForceIDFieldType &&
855
0
            oOptions.eForcedIDFieldType == OFTString)
856
0
        {
857
0
            json_object_object_add(poObj, "id",
858
0
                                   json_object_new_string(CPLSPrintf(
859
0
                                       CPL_FRMT_GIB, poFeature->GetFID())));
860
0
        }
861
0
        else
862
0
        {
863
0
            json_object_object_add(poObj, "id",
864
0
                                   json_object_new_int64(poFeature->GetFID()));
865
0
        }
866
0
    }
867
0
}
868
869
/************************************************************************/
870
/*                      OGRGeoJSONWriteAttributes                       */
871
/************************************************************************/
872
873
json_object *OGRGeoJSONWriteAttributes(OGRFeature *poFeature,
874
                                       bool bWriteIdIfFoundInAttributes,
875
                                       const OGRGeoJSONWriteOptions &oOptions)
876
0
{
877
0
    CPLAssert(nullptr != poFeature);
878
879
0
    json_object *poObjProps = json_object_new_object();
880
0
    CPLAssert(nullptr != poObjProps);
881
882
0
    const OGRFeatureDefn *poDefn = poFeature->GetDefnRef();
883
884
0
    const int nIDField =
885
0
        !oOptions.osIDField.empty()
886
0
            ? poDefn->GetFieldIndexCaseSensitive(oOptions.osIDField)
887
0
            : -1;
888
889
0
    constexpr int MAX_SIGNIFICANT_DIGITS_FLOAT32 = 8;
890
0
    const int nFloat32SignificantDigits =
891
0
        oOptions.nSignificantFigures >= 0
892
0
            ? std::min(oOptions.nSignificantFigures,
893
0
                       MAX_SIGNIFICANT_DIGITS_FLOAT32)
894
0
            : MAX_SIGNIFICANT_DIGITS_FLOAT32;
895
896
0
    const int nFieldCount = poDefn->GetFieldCount();
897
898
0
    json_object *poNativeObjProp = nullptr;
899
0
    json_object *poProperties = nullptr;
900
901
    // Scan the fields to determine if there is a chance of
902
    // mixed types and we can use native media
903
0
    bool bUseNativeMedia{false};
904
905
0
    if (poFeature->GetNativeMediaType() &&
906
0
        OGRIsGeoJSONMediaType(poFeature->GetNativeMediaType()) &&
907
0
        poFeature->GetNativeData())
908
0
    {
909
0
        for (int nField = 0; nField < nFieldCount; ++nField)
910
0
        {
911
0
            if (poDefn->GetFieldDefn(nField)->GetSubType() == OFSTJSON)
912
0
            {
913
0
                if (OGRJSonParse(poFeature->GetNativeData(), &poNativeObjProp,
914
0
                                 false))
915
0
                {
916
0
                    poProperties = OGRGeoJSONFindMemberByName(poNativeObjProp,
917
0
                                                              "properties");
918
0
                    bUseNativeMedia = poProperties != nullptr;
919
0
                }
920
0
                break;
921
0
            }
922
0
        }
923
0
    }
924
925
0
    for (int nField = 0; nField < nFieldCount; ++nField)
926
0
    {
927
0
        if (!poFeature->IsFieldSet(nField) || nField == nIDField)
928
0
        {
929
0
            continue;
930
0
        }
931
932
0
        const OGRFieldDefn *poFieldDefn = poDefn->GetFieldDefn(nField);
933
0
        CPLAssert(nullptr != poFieldDefn);
934
0
        const OGRFieldType eType = poFieldDefn->GetType();
935
0
        const OGRFieldSubType eSubType = poFieldDefn->GetSubType();
936
937
0
        if (!bWriteIdIfFoundInAttributes &&
938
0
            strcmp(poFieldDefn->GetNameRef(), "id") == 0)
939
0
        {
940
0
            continue;
941
0
        }
942
943
0
        json_object *poObjProp = nullptr;
944
945
0
        if (poFeature->IsFieldNull(nField))
946
0
        {
947
            // poObjProp = NULL;
948
0
        }
949
0
        else if (OFTInteger == eType)
950
0
        {
951
0
            if (eSubType == OFSTBoolean)
952
0
                poObjProp = json_object_new_boolean(
953
0
                    poFeature->GetFieldAsInteger(nField));
954
0
            else
955
0
                poObjProp =
956
0
                    json_object_new_int(poFeature->GetFieldAsInteger(nField));
957
0
        }
958
0
        else if (OFTInteger64 == eType)
959
0
        {
960
0
            if (eSubType == OFSTBoolean)
961
0
                poObjProp = json_object_new_boolean(static_cast<json_bool>(
962
0
                    poFeature->GetFieldAsInteger64(nField)));
963
0
            else
964
0
                poObjProp = json_object_new_int64(
965
0
                    poFeature->GetFieldAsInteger64(nField));
966
0
        }
967
0
        else if (OFTReal == eType)
968
0
        {
969
0
            const double val = poFeature->GetFieldAsDouble(nField);
970
0
            if (!std::isfinite(val))
971
0
            {
972
0
                if (!oOptions.bAllowNonFiniteValues)
973
0
                {
974
0
                    CPLErrorOnce(CE_Warning, CPLE_AppDefined,
975
0
                                 "NaN of Infinity value found. Skipped");
976
0
                    continue;
977
0
                }
978
0
            }
979
0
            if (eSubType == OFSTFloat32)
980
0
            {
981
0
                poObjProp = json_object_new_float_with_significant_figures(
982
0
                    static_cast<float>(val), nFloat32SignificantDigits);
983
0
            }
984
0
            else
985
0
            {
986
0
                poObjProp = json_object_new_double_with_significant_figures(
987
0
                    val, oOptions.nSignificantFigures);
988
0
            }
989
0
        }
990
0
        else if (OFTString == eType)
991
0
        {
992
0
            const char *pszStr = poFeature->GetFieldAsString(nField);
993
0
            const size_t nLen = strlen(pszStr);
994
995
0
            if (eSubType == OFSTJSON ||
996
0
                (oOptions.bAutodetectJsonStrings &&
997
0
                 ((pszStr[0] == '{' && pszStr[nLen - 1] == '}') ||
998
0
                  (pszStr[0] == '[' && pszStr[nLen - 1] == ']'))))
999
0
            {
1000
0
                if (bUseNativeMedia)
1001
0
                {
1002
0
                    if (json_object *poProperty = OGRGeoJSONFindMemberByName(
1003
0
                            poProperties, poFieldDefn->GetNameRef()))
1004
0
                    {
1005
0
                        const char *pszProp{json_object_get_string(poProperty)};
1006
0
                        if (pszProp && strcmp(pszProp, pszStr) == 0)
1007
0
                        {
1008
0
                            poObjProp = json_object_get(poProperty);
1009
0
                        }
1010
0
                    }
1011
0
                }
1012
1013
0
                if (poObjProp == nullptr)
1014
0
                {
1015
0
                    if ((pszStr[0] == '{' && pszStr[nLen - 1] == '}') ||
1016
0
                        (pszStr[0] == '[' && pszStr[nLen - 1] == ']'))
1017
0
                    {
1018
0
                        OGRJSonParse(pszStr, &poObjProp, false);
1019
0
                    }
1020
0
                }
1021
0
            }
1022
1023
0
            if (poObjProp == nullptr)
1024
0
                poObjProp = json_object_new_string(pszStr);
1025
0
        }
1026
0
        else if (OFTIntegerList == eType)
1027
0
        {
1028
0
            int nSize = 0;
1029
0
            const int *panList =
1030
0
                poFeature->GetFieldAsIntegerList(nField, &nSize);
1031
0
            poObjProp = json_object_new_array();
1032
0
            for (int i = 0; i < nSize; i++)
1033
0
            {
1034
0
                if (eSubType == OFSTBoolean)
1035
0
                    json_object_array_add(poObjProp,
1036
0
                                          json_object_new_boolean(panList[i]));
1037
0
                else
1038
0
                    json_object_array_add(poObjProp,
1039
0
                                          json_object_new_int(panList[i]));
1040
0
            }
1041
0
        }
1042
0
        else if (OFTInteger64List == eType)
1043
0
        {
1044
0
            int nSize = 0;
1045
0
            const GIntBig *panList =
1046
0
                poFeature->GetFieldAsInteger64List(nField, &nSize);
1047
0
            poObjProp = json_object_new_array();
1048
0
            for (int i = 0; i < nSize; i++)
1049
0
            {
1050
0
                if (eSubType == OFSTBoolean)
1051
0
                    json_object_array_add(
1052
0
                        poObjProp, json_object_new_boolean(
1053
0
                                       static_cast<json_bool>(panList[i])));
1054
0
                else
1055
0
                    json_object_array_add(poObjProp,
1056
0
                                          json_object_new_int64(panList[i]));
1057
0
            }
1058
0
        }
1059
0
        else if (OFTRealList == eType)
1060
0
        {
1061
0
            int nSize = 0;
1062
0
            const double *padfList =
1063
0
                poFeature->GetFieldAsDoubleList(nField, &nSize);
1064
0
            poObjProp = json_object_new_array();
1065
0
            for (int i = 0; i < nSize; i++)
1066
0
            {
1067
0
                if (eSubType == OFSTFloat32)
1068
0
                {
1069
0
                    json_object_array_add(
1070
0
                        poObjProp,
1071
0
                        json_object_new_float_with_significant_figures(
1072
0
                            static_cast<float>(padfList[i]),
1073
0
                            nFloat32SignificantDigits));
1074
0
                }
1075
0
                else
1076
0
                {
1077
0
                    json_object_array_add(
1078
0
                        poObjProp,
1079
0
                        json_object_new_double_with_significant_figures(
1080
0
                            padfList[i], oOptions.nSignificantFigures));
1081
0
                }
1082
0
            }
1083
0
        }
1084
0
        else if (OFTStringList == eType)
1085
0
        {
1086
0
            char **papszStringList = poFeature->GetFieldAsStringList(nField);
1087
0
            poObjProp = json_object_new_array();
1088
0
            for (int i = 0; papszStringList && papszStringList[i]; i++)
1089
0
            {
1090
0
                json_object_array_add(
1091
0
                    poObjProp, json_object_new_string(papszStringList[i]));
1092
0
            }
1093
0
        }
1094
0
        else if (OFTDateTime == eType || OFTDate == eType)
1095
0
        {
1096
0
            char *pszDT = OGRGetXMLDateTime(poFeature->GetRawFieldRef(nField));
1097
0
            if (eType == OFTDate)
1098
0
            {
1099
0
                char *pszT = strchr(pszDT, 'T');
1100
0
                if (pszT)
1101
0
                    *pszT = 0;
1102
0
            }
1103
0
            poObjProp = json_object_new_string(pszDT);
1104
0
            CPLFree(pszDT);
1105
0
        }
1106
0
        else
1107
0
        {
1108
0
            poObjProp =
1109
0
                json_object_new_string(poFeature->GetFieldAsString(nField));
1110
0
        }
1111
1112
0
        json_object_object_add(poObjProps, poFieldDefn->GetNameRef(),
1113
0
                               poObjProp);
1114
0
    }
1115
1116
0
    if (bUseNativeMedia)
1117
0
    {
1118
0
        json_object_put(poNativeObjProp);
1119
0
    }
1120
1121
0
    return poObjProps;
1122
0
}
1123
1124
/************************************************************************/
1125
/*                        GetLinearCollection()                         */
1126
/************************************************************************/
1127
1128
static std::unique_ptr<OGRGeometry>
1129
GetLinearCollection(const OGRGeometryCollection *poGeomColl)
1130
0
{
1131
0
    auto poFlatGeom = std::make_unique<OGRGeometryCollection>();
1132
0
    for (const auto *poSubGeom : *poGeomColl)
1133
0
    {
1134
0
        if (wkbFlatten(poSubGeom->getGeometryType()) == wkbGeometryCollection)
1135
0
        {
1136
0
            poFlatGeom->addGeometry(
1137
0
                GetLinearCollection(poSubGeom->toGeometryCollection()));
1138
0
        }
1139
0
        else
1140
0
        {
1141
0
            auto poNewGeom = OGRGeometryFactory::forceTo(
1142
0
                std::unique_ptr<OGRGeometry>(poSubGeom->clone()),
1143
0
                OGR_GT_GetLinear(poSubGeom->getGeometryType()));
1144
0
            if (poNewGeom)
1145
0
                poFlatGeom->addGeometry(std::move(poNewGeom));
1146
0
        }
1147
0
    }
1148
0
    return poFlatGeom;
1149
0
}
1150
1151
/************************************************************************/
1152
/*                       OGRGeoJSONWriteGeometry                        */
1153
/************************************************************************/
1154
1155
json_object *OGRGeoJSONWriteGeometry(const OGRGeometry *poGeometry,
1156
                                     const OGRGeoJSONWriteOptions &oOptions)
1157
0
{
1158
0
    if (poGeometry == nullptr)
1159
0
    {
1160
0
        CPLAssert(false);
1161
0
        return nullptr;
1162
0
    }
1163
1164
0
    if (!oOptions.bAllowCurve && poGeometry->hasCurveGeometry(true))
1165
0
    {
1166
0
        const OGRwkbGeometryType eTargetType =
1167
0
            OGR_GT_GetLinear(poGeometry->getGeometryType());
1168
0
        std::unique_ptr<OGRGeometry> poFlatGeom;
1169
0
        if (wkbFlatten(eTargetType) == wkbGeometryCollection)
1170
0
        {
1171
0
            poFlatGeom =
1172
0
                GetLinearCollection(poGeometry->toGeometryCollection());
1173
0
        }
1174
0
        else
1175
0
        {
1176
0
            poFlatGeom = OGRGeometryFactory::forceTo(
1177
0
                std::unique_ptr<OGRGeometry>(poGeometry->clone()), eTargetType);
1178
0
        }
1179
0
        return OGRGeoJSONWriteGeometry(poFlatGeom.get(), oOptions);
1180
0
    }
1181
1182
0
    OGRwkbGeometryType eFType = wkbFlatten(poGeometry->getGeometryType());
1183
    // For point empty, return a null geometry. For other empty geometry types,
1184
    // we will generate an empty coordinate array, which is probably also
1185
    // borderline.
1186
0
    if (eFType == wkbPoint && poGeometry->IsEmpty())
1187
0
    {
1188
0
        return nullptr;
1189
0
    }
1190
1191
0
    std::unique_ptr<OGRGeometry> poTmpGeom;  // keep in that scope
1192
0
    if (eFType == wkbCircularString)
1193
0
    {
1194
0
        auto poCS = poGeometry->toCircularString();
1195
0
        const int nNumPoints = poCS->getNumPoints();
1196
0
        constexpr int MAX_POINTS_PER_CC = 11;
1197
0
        if (nNumPoints > MAX_POINTS_PER_CC)
1198
0
        {
1199
0
            auto poCC = std::make_unique<OGRCompoundCurve>();
1200
0
            auto poSubCS = std::make_unique<OGRCircularString>();
1201
0
            for (int i = 0; i < nNumPoints; ++i)
1202
0
            {
1203
0
                OGRPoint oPoint;
1204
0
                poCS->getPoint(i, &oPoint);
1205
0
                poSubCS->addPoint(&oPoint);
1206
0
                if (poSubCS->getNumPoints() == MAX_POINTS_PER_CC)
1207
0
                {
1208
0
                    poCC->addCurve(std::move(poSubCS));
1209
0
                    poSubCS = std::make_unique<OGRCircularString>();
1210
0
                    poSubCS->addPoint(&oPoint);
1211
0
                }
1212
0
            }
1213
0
            if (poSubCS->getNumPoints() > 1)
1214
0
                poCC->addCurve(std::move(poSubCS));
1215
0
            poTmpGeom = std::move(poCC);
1216
0
            poGeometry = poTmpGeom.get();
1217
0
            eFType = wkbCompoundCurve;
1218
0
        }
1219
0
    }
1220
1221
0
    json_object *poObj = json_object_new_object();
1222
0
    CPLAssert(nullptr != poObj);
1223
1224
    /* -------------------------------------------------------------------- */
1225
    /*      Build "type" member of GeoJSON "geometry" object.               */
1226
    /* -------------------------------------------------------------------- */
1227
1228
0
    const char *pszName = OGRGeoJSONGetGeometryName(poGeometry);
1229
0
    json_object_object_add(poObj, "type", json_object_new_string(pszName));
1230
1231
    /* -------------------------------------------------------------------- */
1232
    /*      Build "coordinates" member of GeoJSON "geometry" object.        */
1233
    /* -------------------------------------------------------------------- */
1234
0
    json_object *poObjGeom = nullptr;
1235
1236
0
    if (eFType == wkbGeometryCollection || eFType == wkbMultiCurve ||
1237
0
        eFType == wkbMultiSurface)
1238
0
    {
1239
0
        poObjGeom = OGRGeoJSONWriteGeometryCollection(
1240
0
            poGeometry->toGeometryCollection(), oOptions);
1241
0
        json_object_object_add(poObj, "geometries", poObjGeom);
1242
0
    }
1243
0
    else if (eFType == wkbCompoundCurve)
1244
0
    {
1245
0
        poObjGeom = OGRGeoJSONWriteCompoundCurve(poGeometry->toCompoundCurve(),
1246
0
                                                 oOptions);
1247
0
        json_object_object_add(poObj, "geometries", poObjGeom);
1248
0
    }
1249
0
    else if (eFType == wkbCurvePolygon)
1250
0
    {
1251
0
        poObjGeom =
1252
0
            OGRGeoJSONWriteCurvePolygon(poGeometry->toCurvePolygon(), oOptions);
1253
0
        json_object_object_add(poObj, "geometries", poObjGeom);
1254
0
    }
1255
0
    else
1256
0
    {
1257
0
        if (wkbPoint == eFType)
1258
0
            poObjGeom = OGRGeoJSONWritePoint(poGeometry->toPoint(), oOptions);
1259
0
        else if (wkbLineString == eFType || wkbCircularString == eFType)
1260
0
            poObjGeom = OGRGeoJSONWriteSimpleCurve(poGeometry->toSimpleCurve(),
1261
0
                                                   oOptions);
1262
0
        else if (wkbPolygon == eFType)
1263
0
            poObjGeom =
1264
0
                OGRGeoJSONWritePolygon(poGeometry->toPolygon(), oOptions);
1265
0
        else if (wkbMultiPoint == eFType)
1266
0
            poObjGeom =
1267
0
                OGRGeoJSONWriteMultiPoint(poGeometry->toMultiPoint(), oOptions);
1268
0
        else if (wkbMultiLineString == eFType)
1269
0
            poObjGeom = OGRGeoJSONWriteMultiLineString(
1270
0
                poGeometry->toMultiLineString(), oOptions);
1271
0
        else if (wkbMultiPolygon == eFType)
1272
0
            poObjGeom = OGRGeoJSONWriteMultiPolygon(
1273
0
                poGeometry->toMultiPolygon(), oOptions);
1274
0
        else
1275
0
        {
1276
0
            CPLError(
1277
0
                CE_Failure, CPLE_NotSupported,
1278
0
                "OGR geometry type unsupported as a GeoJSON geometry detected. "
1279
0
                "Feature gets NULL geometry assigned.");
1280
0
        }
1281
1282
0
        if (poObjGeom != nullptr)
1283
0
        {
1284
0
            json_object_object_add(poObj, "coordinates", poObjGeom);
1285
0
        }
1286
0
        else
1287
0
        {
1288
0
            json_object_put(poObj);
1289
0
            poObj = nullptr;
1290
0
        }
1291
0
    }
1292
1293
0
    return poObj;
1294
0
}
1295
1296
/************************************************************************/
1297
/*                         OGRGeoJSONWritePoint                         */
1298
/************************************************************************/
1299
1300
json_object *OGRGeoJSONWritePoint(const OGRPoint *poPoint,
1301
                                  const OGRGeoJSONWriteOptions &oOptions)
1302
0
{
1303
0
    CPLAssert(nullptr != poPoint);
1304
1305
0
    json_object *poObj = nullptr;
1306
1307
    // Generate "coordinates" object
1308
0
    if (!poPoint->IsEmpty())
1309
0
    {
1310
0
        if (oOptions.bAllowMeasure && poPoint->IsMeasured())
1311
0
        {
1312
0
            if (poPoint->Is3D())
1313
0
            {
1314
0
                poObj = OGRGeoJSONWriteCoords(poPoint->getX(), poPoint->getY(),
1315
0
                                              poPoint->getZ(), poPoint->getM(),
1316
0
                                              oOptions);
1317
0
            }
1318
0
            else
1319
0
            {
1320
0
                poObj = OGRGeoJSONWriteCoords(poPoint->getX(), poPoint->getY(),
1321
0
                                              std::nullopt, poPoint->getM(),
1322
0
                                              oOptions);
1323
0
            }
1324
0
        }
1325
0
        else if (poPoint->Is3D())
1326
0
        {
1327
0
            poObj =
1328
0
                OGRGeoJSONWriteCoords(poPoint->getX(), poPoint->getY(),
1329
0
                                      poPoint->getZ(), std::nullopt, oOptions);
1330
0
        }
1331
0
        else
1332
0
        {
1333
0
            poObj = OGRGeoJSONWriteCoords(poPoint->getX(), poPoint->getY(),
1334
0
                                          std::nullopt, std::nullopt, oOptions);
1335
0
        }
1336
0
    }
1337
1338
0
    return poObj;
1339
0
}
1340
1341
/************************************************************************/
1342
/*                      OGRGeoJSONWriteSimpleCurve                      */
1343
/************************************************************************/
1344
1345
json_object *OGRGeoJSONWriteSimpleCurve(const OGRSimpleCurve *poLine,
1346
                                        const OGRGeoJSONWriteOptions &oOptions)
1347
0
{
1348
0
    CPLAssert(nullptr != poLine);
1349
1350
    // Generate "coordinates" object for 2D or 3D dimension.
1351
0
    json_object *poObj = OGRGeoJSONWriteLineCoords(poLine, oOptions);
1352
1353
0
    return poObj;
1354
0
}
1355
1356
/************************************************************************/
1357
/*                        OGRGeoJSONWritePolygon                        */
1358
/************************************************************************/
1359
1360
json_object *OGRGeoJSONWritePolygon(const OGRPolygon *poPolygon,
1361
                                    const OGRGeoJSONWriteOptions &oOptions)
1362
0
{
1363
0
    CPLAssert(nullptr != poPolygon);
1364
1365
    // Generate "coordinates" array object.
1366
0
    json_object *poObj = json_object_new_array();
1367
1368
0
    bool bExteriorRing = true;
1369
0
    for (const auto *poRing : *poPolygon)
1370
0
    {
1371
0
        json_object *poObjRing =
1372
0
            OGRGeoJSONWriteRingCoords(poRing, bExteriorRing, oOptions);
1373
0
        bExteriorRing = false;
1374
0
        if (poObjRing == nullptr)
1375
0
        {
1376
0
            json_object_put(poObj);
1377
0
            return nullptr;
1378
0
        }
1379
0
        json_object_array_add(poObj, poObjRing);
1380
0
    }
1381
1382
0
    return poObj;
1383
0
}
1384
1385
/************************************************************************/
1386
/*                      OGRGeoJSONWriteMultiPoint                       */
1387
/************************************************************************/
1388
1389
json_object *OGRGeoJSONWriteMultiPoint(const OGRMultiPoint *poGeometry,
1390
                                       const OGRGeoJSONWriteOptions &oOptions)
1391
0
{
1392
0
    CPLAssert(nullptr != poGeometry);
1393
1394
    // Generate "coordinates" object
1395
0
    json_object *poObj = json_object_new_array();
1396
1397
0
    for (const auto *poPoint : poGeometry)
1398
0
    {
1399
0
        json_object *poObjPoint = OGRGeoJSONWritePoint(poPoint, oOptions);
1400
0
        if (poObjPoint == nullptr)
1401
0
        {
1402
0
            json_object_put(poObj);
1403
0
            return nullptr;
1404
0
        }
1405
1406
0
        json_object_array_add(poObj, poObjPoint);
1407
0
    }
1408
1409
0
    return poObj;
1410
0
}
1411
1412
/************************************************************************/
1413
/*                    OGRGeoJSONWriteMultiLineString                    */
1414
/************************************************************************/
1415
1416
json_object *
1417
OGRGeoJSONWriteMultiLineString(const OGRMultiLineString *poGeometry,
1418
                               const OGRGeoJSONWriteOptions &oOptions)
1419
0
{
1420
0
    CPLAssert(nullptr != poGeometry);
1421
1422
    // Generate "coordinates" object
1423
0
    json_object *poObj = json_object_new_array();
1424
1425
0
    for (const auto *poLine : poGeometry)
1426
0
    {
1427
0
        json_object *poObjLine = OGRGeoJSONWriteSimpleCurve(poLine, oOptions);
1428
0
        if (poObjLine == nullptr)
1429
0
        {
1430
0
            json_object_put(poObj);
1431
0
            return nullptr;
1432
0
        }
1433
1434
0
        json_object_array_add(poObj, poObjLine);
1435
0
    }
1436
1437
0
    return poObj;
1438
0
}
1439
1440
/************************************************************************/
1441
/*                     OGRGeoJSONWriteMultiPolygon                      */
1442
/************************************************************************/
1443
1444
json_object *OGRGeoJSONWriteMultiPolygon(const OGRMultiPolygon *poGeometry,
1445
                                         const OGRGeoJSONWriteOptions &oOptions)
1446
0
{
1447
0
    CPLAssert(nullptr != poGeometry);
1448
1449
    // Generate "coordinates" object
1450
0
    json_object *poObj = json_object_new_array();
1451
1452
0
    for (const auto *poPoly : poGeometry)
1453
0
    {
1454
0
        json_object *poObjPoly = OGRGeoJSONWritePolygon(poPoly, oOptions);
1455
0
        if (poObjPoly == nullptr)
1456
0
        {
1457
0
            json_object_put(poObj);
1458
0
            return nullptr;
1459
0
        }
1460
1461
0
        json_object_array_add(poObj, poObjPoly);
1462
0
    }
1463
1464
0
    return poObj;
1465
0
}
1466
1467
/************************************************************************/
1468
/*                  OGRGeoJSONWriteCollectionGeneric()                  */
1469
/************************************************************************/
1470
1471
template <class T>
1472
static json_object *
1473
OGRGeoJSONWriteCollectionGeneric(const T *poGeometry,
1474
                                 const OGRGeoJSONWriteOptions &oOptions)
1475
0
{
1476
0
    CPLAssert(nullptr != poGeometry);
1477
1478
    /* Generate "geometries" object. */
1479
0
    json_object *poObj = json_object_new_array();
1480
1481
0
    for (const OGRGeometry *poGeom : *poGeometry)
1482
0
    {
1483
0
        json_object *poObjGeom = OGRGeoJSONWriteGeometry(poGeom, oOptions);
1484
0
        if (poObjGeom == nullptr)
1485
0
        {
1486
0
            json_object_put(poObj);
1487
0
            return nullptr;
1488
0
        }
1489
1490
0
        json_object_array_add(poObj, poObjGeom);
1491
0
    }
1492
1493
0
    return poObj;
1494
0
}
Unexecuted instantiation: ogrgeojsonwriter.cpp:json_object* OGRGeoJSONWriteCollectionGeneric<OGRGeometryCollection>(OGRGeometryCollection const*, OGRGeoJSONWriteOptions const&)
Unexecuted instantiation: ogrgeojsonwriter.cpp:json_object* OGRGeoJSONWriteCollectionGeneric<OGRCompoundCurve>(OGRCompoundCurve const*, OGRGeoJSONWriteOptions const&)
Unexecuted instantiation: ogrgeojsonwriter.cpp:json_object* OGRGeoJSONWriteCollectionGeneric<OGRCurvePolygon>(OGRCurvePolygon const*, OGRGeoJSONWriteOptions const&)
1495
1496
/************************************************************************/
1497
/*                  OGRGeoJSONWriteGeometryCollection                   */
1498
/************************************************************************/
1499
1500
json_object *
1501
OGRGeoJSONWriteGeometryCollection(const OGRGeometryCollection *poGeometry,
1502
                                  const OGRGeoJSONWriteOptions &oOptions)
1503
0
{
1504
0
    return OGRGeoJSONWriteCollectionGeneric(poGeometry, oOptions);
1505
0
}
1506
1507
/************************************************************************/
1508
/*                     OGRGeoJSONWriteCompoundCurve                     */
1509
/************************************************************************/
1510
1511
json_object *
1512
OGRGeoJSONWriteCompoundCurve(const OGRCompoundCurve *poGeometry,
1513
                             const OGRGeoJSONWriteOptions &oOptions)
1514
0
{
1515
0
    return OGRGeoJSONWriteCollectionGeneric(poGeometry, oOptions);
1516
0
}
1517
1518
/************************************************************************/
1519
/*                     OGRGeoJSONWriteCurvePolygon                      */
1520
/************************************************************************/
1521
1522
json_object *OGRGeoJSONWriteCurvePolygon(const OGRCurvePolygon *poGeometry,
1523
                                         const OGRGeoJSONWriteOptions &oOptions)
1524
0
{
1525
0
    return OGRGeoJSONWriteCollectionGeneric(poGeometry, oOptions);
1526
0
}
1527
1528
/************************************************************************/
1529
/*                        OGRGeoJSONWriteCoords                         */
1530
/************************************************************************/
1531
1532
json_object *OGRGeoJSONWriteCoords(double dfX, double dfY,
1533
                                   std::optional<double> dfZ,
1534
                                   std::optional<double> dfM,
1535
                                   const OGRGeoJSONWriteOptions &oOptions)
1536
0
{
1537
0
    json_object *poObjCoords = nullptr;
1538
0
    if (!std::isfinite(dfX) || !std::isfinite(dfY) ||
1539
0
        (dfZ && !std::isfinite(*dfZ)) || (dfM && !std::isfinite(*dfM)))
1540
0
    {
1541
0
        CPLError(CE_Warning, CPLE_AppDefined,
1542
0
                 "Infinite or NaN coordinate encountered");
1543
0
        return nullptr;
1544
0
    }
1545
0
    poObjCoords = json_object_new_array();
1546
0
    json_object_array_add(poObjCoords, json_object_new_coord(dfX, 1, oOptions));
1547
0
    json_object_array_add(poObjCoords, json_object_new_coord(dfY, 2, oOptions));
1548
0
    int nIdx = 3;
1549
0
    if (dfZ)
1550
0
    {
1551
0
        json_object_array_add(poObjCoords,
1552
0
                              json_object_new_coord(*dfZ, nIdx, oOptions));
1553
0
        nIdx++;
1554
0
    }
1555
0
    if (dfM)
1556
0
    {
1557
0
        json_object_array_add(poObjCoords,
1558
0
                              json_object_new_coord(*dfM, nIdx, oOptions));
1559
0
    }
1560
1561
0
    return poObjCoords;
1562
0
}
1563
1564
/************************************************************************/
1565
/*                      OGRGeoJSONWriteLineCoords                       */
1566
/************************************************************************/
1567
1568
json_object *OGRGeoJSONWriteLineCoords(const OGRSimpleCurve *poLine,
1569
                                       const OGRGeoJSONWriteOptions &oOptions)
1570
0
{
1571
0
    json_object *poObjCoords = json_object_new_array();
1572
1573
0
    const int nCount = poLine->getNumPoints();
1574
0
    const auto bHasZ = poLine->Is3D();
1575
0
    const auto bHasM = oOptions.bAllowMeasure && poLine->IsMeasured();
1576
0
    for (int i = 0; i < nCount; ++i)
1577
0
    {
1578
0
        json_object *poObjPoint;
1579
0
        if (bHasZ)
1580
0
        {
1581
0
            if (bHasM)
1582
0
            {
1583
0
                poObjPoint = OGRGeoJSONWriteCoords(
1584
0
                    poLine->getX(i), poLine->getY(i), poLine->getZ(i),
1585
0
                    poLine->getM(i), oOptions);
1586
0
            }
1587
0
            else
1588
0
            {
1589
0
                poObjPoint = OGRGeoJSONWriteCoords(
1590
0
                    poLine->getX(i), poLine->getY(i), poLine->getZ(i),
1591
0
                    std::nullopt, oOptions);
1592
0
            }
1593
0
        }
1594
0
        else if (bHasM)
1595
0
        {
1596
0
            poObjPoint =
1597
0
                OGRGeoJSONWriteCoords(poLine->getX(i), poLine->getY(i),
1598
0
                                      std::nullopt, poLine->getM(i), oOptions);
1599
0
        }
1600
0
        else
1601
0
        {
1602
0
            poObjPoint =
1603
0
                OGRGeoJSONWriteCoords(poLine->getX(i), poLine->getY(i),
1604
0
                                      std::nullopt, std::nullopt, oOptions);
1605
0
        }
1606
0
        if (poObjPoint == nullptr)
1607
0
        {
1608
0
            json_object_put(poObjCoords);
1609
0
            return nullptr;
1610
0
        }
1611
0
        json_object_array_add(poObjCoords, poObjPoint);
1612
0
    }
1613
1614
0
    return poObjCoords;
1615
0
}
1616
1617
/************************************************************************/
1618
/*                      OGRGeoJSONWriteRingCoords                       */
1619
/************************************************************************/
1620
1621
json_object *OGRGeoJSONWriteRingCoords(const OGRLinearRing *poLine,
1622
                                       bool bIsExteriorRing,
1623
                                       const OGRGeoJSONWriteOptions &oOptions)
1624
0
{
1625
0
    json_object *poObjCoords = json_object_new_array();
1626
1627
0
    const bool bInvertOrder = oOptions.bPolygonRightHandRule &&
1628
0
                              ((bIsExteriorRing && poLine->isClockwise()) ||
1629
0
                               (!bIsExteriorRing && !poLine->isClockwise()));
1630
1631
0
    const int nCount = poLine->getNumPoints();
1632
0
    const auto bHasZ = poLine->Is3D();
1633
0
    const auto bHasM = oOptions.bAllowMeasure && poLine->IsMeasured();
1634
0
    for (int i = 0; i < nCount; ++i)
1635
0
    {
1636
0
        const int nIdx = (bInvertOrder) ? nCount - 1 - i : i;
1637
0
        json_object *poObjPoint;
1638
0
        if (bHasZ)
1639
0
        {
1640
0
            if (bHasM)
1641
0
            {
1642
0
                poObjPoint = OGRGeoJSONWriteCoords(
1643
0
                    poLine->getX(nIdx), poLine->getY(nIdx), poLine->getZ(nIdx),
1644
0
                    poLine->getM(nIdx), oOptions);
1645
0
            }
1646
0
            else
1647
0
            {
1648
0
                poObjPoint = OGRGeoJSONWriteCoords(
1649
0
                    poLine->getX(nIdx), poLine->getY(nIdx), poLine->getZ(nIdx),
1650
0
                    std::nullopt, oOptions);
1651
0
            }
1652
0
        }
1653
0
        else if (bHasM)
1654
0
        {
1655
0
            poObjPoint = OGRGeoJSONWriteCoords(poLine->getX(nIdx),
1656
0
                                               poLine->getY(nIdx), std::nullopt,
1657
0
                                               poLine->getM(nIdx), oOptions);
1658
0
        }
1659
0
        else
1660
0
        {
1661
0
            poObjPoint =
1662
0
                OGRGeoJSONWriteCoords(poLine->getX(nIdx), poLine->getY(nIdx),
1663
0
                                      std::nullopt, std::nullopt, oOptions);
1664
0
        }
1665
0
        if (poObjPoint == nullptr)
1666
0
        {
1667
0
            json_object_put(poObjCoords);
1668
0
            return nullptr;
1669
0
        }
1670
0
        json_object_array_add(poObjCoords, poObjPoint);
1671
0
    }
1672
1673
0
    return poObjCoords;
1674
0
}
1675
1676
/************************************************************************/
1677
/*         OGR_json_float_with_significant_figures_to_string()          */
1678
/************************************************************************/
1679
1680
static int OGR_json_float_with_significant_figures_to_string(
1681
    struct json_object *jso, struct printbuf *pb, int /* level */,
1682
    int /* flags */)
1683
0
{
1684
0
    char szBuffer[75] = {};
1685
0
    int nSize = 0;
1686
0
    const float fVal = static_cast<float>(json_object_get_double(jso));
1687
0
    if (std::isnan(fVal))
1688
0
        nSize = CPLsnprintf(szBuffer, sizeof(szBuffer), "NaN");
1689
0
    else if (std::isinf(fVal))
1690
0
    {
1691
0
        if (fVal > 0)
1692
0
            nSize = CPLsnprintf(szBuffer, sizeof(szBuffer), "Infinity");
1693
0
        else
1694
0
            nSize = CPLsnprintf(szBuffer, sizeof(szBuffer), "-Infinity");
1695
0
    }
1696
0
    else
1697
0
    {
1698
0
        const void *userData =
1699
#if (!defined(JSON_C_VERSION_NUM)) || (JSON_C_VERSION_NUM < JSON_C_VER_013)
1700
            jso->_userdata;
1701
#else
1702
0
            json_object_get_userdata(jso);
1703
0
#endif
1704
0
        const uintptr_t nSignificantFigures =
1705
0
            reinterpret_cast<uintptr_t>(userData);
1706
0
        const bool bSignificantFiguresIsNegative =
1707
0
            (nSignificantFigures >> (8 * sizeof(nSignificantFigures) - 1)) != 0;
1708
0
        const int nInitialSignificantFigures =
1709
0
            bSignificantFiguresIsNegative
1710
0
                ? 8
1711
0
                : static_cast<int>(nSignificantFigures);
1712
0
        nSize = OGRFormatFloat(szBuffer, sizeof(szBuffer), fVal,
1713
0
                               nInitialSignificantFigures, 'g');
1714
0
    }
1715
1716
0
    return printbuf_memappend(pb, szBuffer, nSize);
1717
0
}
1718
1719
/************************************************************************/
1720
/*           json_object_new_float_with_significant_figures()           */
1721
/************************************************************************/
1722
1723
json_object *
1724
json_object_new_float_with_significant_figures(float fVal,
1725
                                               int nSignificantFigures)
1726
0
{
1727
0
    json_object *jso = json_object_new_double(double(fVal));
1728
0
    json_object_set_serializer(
1729
0
        jso, OGR_json_float_with_significant_figures_to_string,
1730
0
        reinterpret_cast<void *>(static_cast<uintptr_t>(nSignificantFigures)),
1731
0
        nullptr);
1732
0
    return jso;
1733
0
}
1734
1735
/*! @endcond */
1736
1737
/************************************************************************/
1738
/*                          OGR_G_ExportToJson                          */
1739
/************************************************************************/
1740
1741
/**
1742
 * \brief Convert a geometry into GeoJSON format.
1743
 *
1744
 * The returned string should be freed with CPLFree() when no longer required.
1745
 *
1746
 * This method is the same as the C++ method OGRGeometry::exportToJson().
1747
 *
1748
 * @param hGeometry handle to the geometry.
1749
 * @return A GeoJSON fragment or NULL in case of error.
1750
 */
1751
1752
char *OGR_G_ExportToJson(OGRGeometryH hGeometry)
1753
0
{
1754
0
    return OGR_G_ExportToJsonEx(hGeometry, nullptr);
1755
0
}
1756
1757
/************************************************************************/
1758
/*                         OGR_G_ExportToJsonEx                         */
1759
/************************************************************************/
1760
1761
/**
1762
 * \brief Convert a geometry into GeoJSON-style format.
1763
 *
1764
 * The returned string should be freed with CPLFree() when no longer required.
1765
 *
1766
 * If setting ALLOW_CURVE=YES and ALLOW_MEASURE=YES, the result is compatible
1767
 * of JSON-FG geometries. If there is a SRS attached to the geometry, and the
1768
 * geometry is aimed at being stored in the "place" member of JSON-FG features,
1769
 * then the COORDINATE_ORDER option must be set to AUTHORITY_COMPLIANT.
1770
 *
1771
 * The following options are supported :
1772
 * <ul>
1773
 * <li>COORDINATE_PRECISION=number: maximum number of figures after decimal
1774
 * separator to write in coordinates.</li>
1775
 * <li>XY_COORD_PRECISION=integer: number of decimal figures for X,Y coordinates
1776
 * (added in GDAL 3.9)</li>
1777
 * <li>Z_COORD_PRECISION=integer: number of decimal figures for Z coordinates
1778
 * (added in GDAL 3.9)</li>
1779
 * <li>SIGNIFICANT_FIGURES=number: maximum number of significant figures.</li>
1780
 * <li>ALLOW_CURVE=YES/NO: whether curve geometries are allowed. When set to NO
1781
 * (its default value), they are converted to linear geometries first.
1782
 * Curves are not allowed in GeoJSON, but they are in JSON-FG geometries.
1783
 * (added in GDAL 3.12.1)</li>
1784
 * <li>ALLOW_MEASURE=YES/NO: whether the measure (M) component of geometries is
1785
 * allowed. When set to NO (its default value), it is dropped when present.
1786
 * Measures are not allowed in GeoJSON, but they are in JSON-FG geometries.
1787
 * (added in GDAL 3.12.1)</li>
1788
 * <li>COORDINATE_ORDER=TRADITIONAL_GIS_ORDER/AUTHORITY_COMPLIANT (added in GDAL 3.12.1):
1789
 * When a SRS is attached to the geometry, and AUTHORITY_COMPLIANT is used,
1790
 * the coordinates will be emitted in the order of the official SRS definition.
1791
 * When using TRADITIONAL_GIS_ORDER (the default), coordinates are emitted in
1792
 * longitude/easting first, latitude/northing second.
1793
 * When no SRS is attached, coordinates are emitted in the order they are set
1794
 * in the geometry.
1795
 * When this function is used to emit JSON-FG geometries stored in the "place"
1796
 * member, this option must be set to AUTHORITY_COMPLIANT if there is a SRS
1797
 * attached to the geometry.
1798
 * </li>
1799
 * </ul>
1800
 *
1801
 * If XY_COORD_PRECISION or Z_COORD_PRECISION is specified, COORDINATE_PRECISION
1802
 * or SIGNIFICANT_FIGURES will be ignored if specified.
1803
 * If COORDINATE_PRECISION is defined, SIGNIFICANT_FIGURES will be ignored if
1804
 * specified.
1805
 * When none are defined, the default is COORDINATE_PRECISION=15.
1806
 *
1807
 * This method is the same as the C++ method OGRGeometry::exportToJson().
1808
 *
1809
 * @param hGeometry handle to the geometry.
1810
 * @param papszOptions a null terminated list of options.
1811
 * @return A GeoJSON fragment or NULL in case of error.
1812
 *
1813
 */
1814
1815
char *OGR_G_ExportToJsonEx(OGRGeometryH hGeometry, CSLConstList papszOptions)
1816
0
{
1817
0
    VALIDATE_POINTER1(hGeometry, "OGR_G_ExportToJson", nullptr);
1818
1819
0
    OGRGeometry *poGeometry = OGRGeometry::FromHandle(hGeometry);
1820
1821
0
    const char *pszCoordPrecision =
1822
0
        CSLFetchNameValueDef(papszOptions, "COORDINATE_PRECISION", "-1");
1823
1824
0
    const int nSignificantFigures =
1825
0
        atoi(CSLFetchNameValueDef(papszOptions, "SIGNIFICANT_FIGURES", "-1"));
1826
1827
0
    OGRGeoJSONWriteOptions oOptions;
1828
0
    oOptions.nXYCoordPrecision = atoi(CSLFetchNameValueDef(
1829
0
        papszOptions, "XY_COORD_PRECISION", pszCoordPrecision));
1830
0
    oOptions.nZCoordPrecision = atoi(CSLFetchNameValueDef(
1831
0
        papszOptions, "Z_COORD_PRECISION", pszCoordPrecision));
1832
0
    oOptions.nSignificantFigures = nSignificantFigures;
1833
0
    oOptions.bAllowCurve =
1834
0
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "ALLOW_CURVE", "NO"));
1835
0
    oOptions.bAllowMeasure =
1836
0
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "ALLOW_MEASURE", "NO"));
1837
1838
0
    bool bHasSwappedXY = false;
1839
0
    const char *pszCoordinateOrder = CSLFetchNameValueDef(
1840
0
        papszOptions, "COORDINATE_ORDER", "TRADITIONAL_GIS_ORDER");
1841
0
    if (EQUAL(pszCoordinateOrder, "TRADITIONAL_GIS_ORDER"))
1842
0
    {
1843
        // If the CRS has latitude, longitude (or northing, easting) axis order,
1844
        // and the data axis to SRS axis mapping doesn't change that order,
1845
        // then swap X and Y values.
1846
0
        const auto poSRS = poGeometry->getSpatialReference();
1847
0
        if (poSRS && (poSRS->EPSGTreatsAsLatLong() ||
1848
0
                      poSRS->EPSGTreatsAsNorthingEasting()))
1849
0
        {
1850
0
            auto anMapping =
1851
0
                std::vector<int>(poSRS->GetDataAxisToSRSAxisMapping());
1852
0
            anMapping.resize(2);
1853
0
            if (anMapping == std::vector<int>{1, 2})
1854
0
            {
1855
0
                poGeometry->swapXY();
1856
0
                bHasSwappedXY = true;
1857
0
            }
1858
0
        }
1859
0
    }
1860
0
    else if (EQUAL(pszCoordinateOrder, "AUTHORITY_COMPLIANT"))
1861
0
    {
1862
0
        const auto poSRS = poGeometry->getSpatialReference();
1863
0
        if (poSRS && (poSRS->EPSGTreatsAsLatLong() ||
1864
0
                      poSRS->EPSGTreatsAsNorthingEasting()))
1865
0
        {
1866
0
            auto anMapping =
1867
0
                std::vector<int>(poSRS->GetDataAxisToSRSAxisMapping());
1868
0
            anMapping.resize(2);
1869
0
            if (anMapping == std::vector<int>{2, 1})
1870
0
            {
1871
0
                poGeometry->swapXY();
1872
0
                bHasSwappedXY = true;
1873
0
            }
1874
0
        }
1875
0
    }
1876
0
    else
1877
0
    {
1878
0
        CPLError(CE_Failure, CPLE_NotSupported,
1879
0
                 "Unsupported COORDINATE_ORDER='%s'", pszCoordinateOrder);
1880
0
        return nullptr;
1881
0
    }
1882
1883
0
    json_object *poObj = OGRGeoJSONWriteGeometry(poGeometry, oOptions);
1884
1885
    // Unswap back
1886
0
    if (bHasSwappedXY)
1887
0
        poGeometry->swapXY();
1888
1889
0
    if (nullptr != poObj)
1890
0
    {
1891
0
        char *pszJson = CPLStrdup(json_object_to_json_string(poObj));
1892
1893
        // Release JSON tree.
1894
0
        json_object_put(poObj);
1895
1896
0
        return pszJson;
1897
0
    }
1898
1899
    // Translation failed.
1900
0
    return nullptr;
1901
0
}