-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmapcoder.c
More file actions
3801 lines (3410 loc) · 139 KB
/
mapcoder.c
File metadata and controls
3801 lines (3410 loc) · 139 KB
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2014-2025 Stichting Mapcode Foundation (http://www.mapcode.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file mapcoder.c
* @brief Core implementation of the Mapcode encoding and decoding system
*
* This file contains the complete implementation of the Mapcode system, which provides
* a way to encode any location on Earth into a short alphanumeric code and decode
* it back to precise coordinates.
*
* Key functionality includes:
* - Encoding latitude/longitude coordinates to mapcode strings
* - Decoding mapcode strings back to coordinates
* - Territory-based encoding for shorter codes within specific regions
* - Support for high-precision encoding with extra digits
* - Multi-alphabet support for international usage
* - Territory name handling and lookup functions
*
* The encoding uses a sophisticated grid system that divides the Earth's surface
* into increasingly fine grids, with special handling for different territory
* shapes and boundary conditions.
*
* @author Stichting Mapcode Foundation
* @version See MAPCODE_C_VERSION constant
*/
#include <string.h> // strlen strcpy strcat memcpy memmove strstr strchr memcmp
#include <stdlib.h> // atof
#include <ctype.h> // toupper
#include <math.h> // floor fabs
#include "mapcoder.h"
#include "internal_data.h"
#include "internal_iso3166_data.h"
#include "internal_territory_alphabets.h"
#include "internal_territory_names_local.h"
#include "internal_alphabet_recognizer.h"
#include "internal_territory_names_af.h"
#include "internal_territory_names_ar.h"
#include "internal_territory_names_be.h"
#include "internal_territory_names_cn.h"
#include "internal_territory_names_cs.h"
#include "internal_territory_names_da.h"
#include "internal_territory_names_de.h"
#include "internal_territory_names_en.h"
#include "internal_territory_names_es.h"
#include "internal_territory_names_fi.h"
#include "internal_territory_names_fr.h"
#include "internal_territory_names_he.h"
#include "internal_territory_names_hi.h"
#include "internal_territory_names_hr.h"
#include "internal_territory_names_id.h"
#include "internal_territory_names_it.h"
#include "internal_territory_names_ja.h"
#include "internal_territory_names_ko.h"
#include "internal_territory_names_nl.h"
#include "internal_territory_names_no.h"
#include "internal_territory_names_pl.h"
#include "internal_territory_names_pt.h"
#include "internal_territory_names_ru.h"
#include "internal_territory_names_sv.h"
#include "internal_territory_names_sw.h"
#include "internal_territory_names_tr.h"
#include "internal_territory_names_uk.h"
/**
* @section exported_constants Exported Constants
* The constants are also exported as variables to allow other languages to use them.
* This provides runtime access to compile-time constants for language bindings.
*/
char* _MAPCODE_C_VERSION = MAPCODE_C_VERSION; // Version string of the mapcode library
int _MAX_NR_OF_MAPCODE_RESULTS = MAX_NR_OF_MAPCODE_RESULTS; // Maximum number of mapcode results returned
int _MAX_PRECISION_DIGITS = MAX_PRECISION_DIGITS; // Maximum extra precision digits supported
int _MAX_PROPER_MAPCODE_ASCII_LEN = MAX_PROPER_MAPCODE_ASCII_LEN; // Maximum length of a proper mapcode in ASCII
int _MAX_ISOCODE_ASCII_LEN = MAX_ISOCODE_ASCII_LEN; // Maximum length of ISO territory code
int _MAX_CLEAN_MAPCODE_ASCII_LEN = MAX_CLEAN_MAPCODE_ASCII_LEN; // Maximum length of clean mapcode (no territory)
int _MAX_MAPCODE_RESULT_ASCII_LEN = MAX_MAPCODE_RESULT_ASCII_LEN; // Maximum length of complete result string
int _MAX_TERRITORY_FULLNAME_UTF8_LEN = MAX_TERRITORY_FULLNAME_UTF8_LEN; // Maximum territory name length in UTF-8
int _MAX_MAPCODE_RESULT_UTF8_LEN = MAX_MAPCODE_RESULT_UTF8_LEN; // Maximum result length in UTF-8
int _MAX_MAPCODE_RESULT_UTF16_LEN = MAX_MAPCODE_RESULT_UTF16_LEN; // Maximum result length in UTF-16
int _MAX_ALPHABETS_PER_TERRITORY = MAX_ALPHABETS_PER_TERRITORY; // Maximum alphabets supported per territory
/**
* @section debug_system Debug and Assertion System
* Debug mode provides runtime assertion checking to catch programming errors
* during development and testing.
*/
#ifdef DEBUG
#include <stdio.h>
/**
* @brief Debug assertion function that tracks and reports failed conditions
* @param iCondition The condition to test (should be true)
* @param cstrFile Source file where assertion occurred
* @param iLine Line number where assertion occurred
*
* This function provides detailed error reporting when assertions fail in debug mode.
* It keeps track of assertion failures and terminates the program after too many
* failures to prevent cascading errors.
*/
void _TestAssert(int iCondition, const char* cstrFile, int iLine) {
static int nrAsserts = 0;
if (!iCondition) {
fprintf(stderr, "** Assertion failed: file \"%s\", line %d\n", cstrFile, iLine);
++nrAsserts;
if (nrAsserts >= 25) {
fprintf(stderr, "** Stopped execution after %d assertions!\n", nrAsserts);
exit(-1);
}
}
}
// In debug mode, assertions are active and report failures
#define ASSERT(condition) _TestAssert((int) (condition), __FILE__, (int) __LINE__)
#else
// In release mode, assertions are compiled out for performance
#define ASSERT(condition)
#endif
// If you do not want to use the fast encoding from internal_territory_search.h, define NO_FAST_ENCODE on the
// command-line of your compiler (or uncomment the following line).
// #define NO_FAST_ENCODE
#ifndef NO_FAST_ENCODE
#include "internal_territory_search.h"
#endif
/**
* @section territory_flag_macros Territory Boundary Flag Extraction Macros
* These macros extract specific information from the flags field of territory boundary records.
* Each territory has flags that encode various properties used during encoding/decoding.
*/
#define IS_NAMELESS(m) (TERRITORY_BOUNDARIES[m].flags & 64) // Territory uses nameless encoding (bit 6)
#define IS_RESTRICTED(m) (TERRITORY_BOUNDARIES[m].flags & 512) // Territory has access restrictions (bit 9)
#define IS_SPECIAL_SHAPE(m) (TERRITORY_BOUNDARIES[m].flags & 1024) // Territory has non-standard shape (bit 10)
#define REC_TYPE(m) ((TERRITORY_BOUNDARIES[m].flags >> 7) & 3) // Record type (bits 7-8): grid encoding method
#define SMART_DIV(m) (TERRITORY_BOUNDARIES[m].flags >> 16) // Smart divider value (bits 16+): grid subdivision
#define HEADER_LETTER(m) (ENCODE_CHARS[(TERRITORY_BOUNDARIES[m].flags >> 11) & 31]) // Header letter for encoding (bits 11-15)
/**
* @section parsing_tokens Token Types for Mapcode Parsing
* These constants define different types of tokens encountered during mapcode parsing.
*/
#define TOKENSEP 0 // Separator character (space, hyphen, etc.)
#define TOKENDOT 1 // Dot character '.'
#define TOKENCHR 2 // Regular character (consonant or digit)
#define TOKENVOWEL 3 // Vowel character (A, E, U)
#define TOKENZERO 4 // Zero digit '0'
#define TOKENHYPH 5 // Hyphen character '-'
/**
* @section parsing_state Parsing State Constants
*/
#define STATE_GO 31 // Active parsing state identifier
/**
* @section mathematical_constants Mathematical and Earth Constants
* Fundamental constants used in coordinate calculations and grid mathematics.
*/
#define MATH_PI 3.14159265358979323846 // High-precision value of π
#define MAX_PRECISION_FACTOR 810000 // 30^(MAX_PRECISION_DIGITS/2) - base precision factor
// Earth's radius in meters (WGS84 ellipsoid approximation)
#define EARTH_RADIUS_X_METERS 6378137 // Equatorial radius (semi-major axis)
#define EARTH_RADIUS_Y_METERS 6356752 // Polar radius (semi-minor axis)
// Earth's circumference in meters
#define EARTH_CIRCUMFERENCE_X (EARTH_RADIUS_X_METERS * 2 * MATH_PI) // Equatorial circumference
#define EARTH_CIRCUMFERENCE_Y (EARTH_RADIUS_Y_METERS * 2 * MATH_PI) // Meridional circumference
/**
* @section coordinate_conversion Coordinate Conversion Factors
* Factors for converting between different coordinate representations.
*/
#define MICROLAT_TO_FRACTIONS_FACTOR ((double) MAX_PRECISION_FACTOR) // Convert latitude microdegrees to fractions
#define MICROLON_TO_FRACTIONS_FACTOR (4.0 * MAX_PRECISION_FACTOR) // Convert longitude microdegrees to fractions
/**
* @section grid_encoding_constants Grid and Encoding Constants
* These constants define the fundamental grid structure used in mapcode encoding.
* The mapcode system uses a base-31 grid system that recursively subdivides space.
*/
#define GRID_SIZE_31 31 // Base grid size: 31x31 grid cells (base-31 encoding)
#define GRID_SIZE_961 961 // 31^2 = 961 - second level grid size
#define GRID_SIZE_962 962 // 961 + 1 - used for boundary calculations
#define GRID_SIZE_SQUARED (961 * 961) // 961^2 - third level grid size for fine precision
#define MAX_NAMELESS_RECORDS 62 // Maximum nameless territory records in subdivision
#define Y_DIVIDER 90 // Standard latitude divider for grid calculations
#define SPECIAL_CODEX_21 21 // Special encoding method identifier (type 21)
#define SPECIAL_CODEX_22 22 // Special encoding method identifier (type 22)
#define SPECIAL_CODEX_13 13 // Special encoding method identifier (type 13)
#define SPECIAL_CODEX_14 14 // Special encoding method identifier (type 14)
#define GRID_MULTIPLIER_16 16 // Multiplier for grid offset calculations
/**
* @section string_encoding_flags String Encoding Type Flags
* Flags to distinguish between different string encoding formats.
*/
#define FLAG_UTF8_STRING 0 // Interpret string pointer as UTF-8 characters
#define FLAG_UTF16_STRING 1 // Interpret string pointer as UTF-16 characters
/**
* @section distance_calculation Distance Calculation Constants
* Meters per degree latitude is constant globally. For longitude, the actual
* distance varies by latitude, so use factor * cos(midpoint_latitude).
*/
static const double METERS_PER_DEGREE_LAT = EARTH_CIRCUMFERENCE_Y / 360.0; // ~111,319 meters per degree latitude
static const double METERS_PER_DEGREE_LON = EARTH_CIRCUMFERENCE_X / 360.0; // ~111,320 meters per degree longitude at equator
/**
* @section debug_control Debug Control Variables
*/
static const int DEBUG_STOP_AT = -1; // Internal debug limit for encoding tests (do not use in production!)
/**
* @section locale_support Locale and Language Support Structures
* These structures support multi-language territory names for international usage.
*/
/**
* @brief Registry item linking a locale identifier to territory name translations
* @param locale Two-character locale identifier (e.g., "EN", "FR", "DE")
* @param territoryFullNames Array of translated territory names for this locale
*/
typedef struct {
const char* locale; // Language/locale identifier
const char** territoryFullNames; // Array of territory names in this language
} LocaleRegistryItem;
/**
* @brief Registry of supported locales and their territory name translations
* This array maps two-character locale codes to arrays of translated territory names.
* Supports major world languages for international mapcode applications.
*/
static const LocaleRegistryItem LOCALE_REGISTRY[] = {
{"AF", TERRITORY_FULL_NAME_AF}, // Afrikaans
{"AR", TERRITORY_FULL_NAME_AR}, // Arabic
{"BE", TERRITORY_FULL_NAME_BE}, // Belarusian
{"CN", TERRITORY_FULL_NAME_CN}, // Chinese (Simplified)
{"CS", TERRITORY_FULL_NAME_CS}, // Czech
{"DA", TERRITORY_FULL_NAME_DA}, // Danish
{"DE", TERRITORY_FULL_NAME_DE}, // German
{"EN", TERRITORY_FULL_NAME_EN}, // English
{"ES", TERRITORY_FULL_NAME_ES}, // Spanish
{"FI", TERRITORY_FULL_NAME_FI}, // Finnish
{"FR", TERRITORY_FULL_NAME_FR}, // French
{"HE", TERRITORY_FULL_NAME_HE}, // Hebrew
{"HI", TERRITORY_FULL_NAME_HI}, // Hindi
{"HR", TERRITORY_FULL_NAME_HR}, // Croatian
{"ID", TERRITORY_FULL_NAME_ID}, // Indonesian
{"IT", TERRITORY_FULL_NAME_IT}, // Italian
{"JA", TERRITORY_FULL_NAME_JA}, // Japanese
{"KO", TERRITORY_FULL_NAME_KO}, // Korean
{"NL", TERRITORY_FULL_NAME_NL}, // Dutch
{"NO", TERRITORY_FULL_NAME_NO}, // Norwegian
{"PT", TERRITORY_FULL_NAME_PT}, // Portuguese
{"PL", TERRITORY_FULL_NAME_PL}, // Polish
{"RU", TERRITORY_FULL_NAME_RU}, // Russian
{"SV", TERRITORY_FULL_NAME_SV}, // Swedish
{"SW", TERRITORY_FULL_NAME_SW}, // Swahili
{"TR", TERRITORY_FULL_NAME_TR}, // Turkish
{"UK", TERRITORY_FULL_NAME_UK} // Ukrainian
};
/**
* @section parent_territories Parent Territory Information
* The 8 major parent territories that contain subdivisions with shorter mapcodes.
* These large countries/regions are subdivided to allow shorter codes within them.
*/
/**
* @brief Three-letter ISO codes for parent territories
* Comma-separated string of 3-letter ISO codes for the 8 major parent territories
*/
static const char* PARENTS_3 = "USA,IND,CAN,AUS,MEX,BRA,RUS,CHN,";
/**
* @brief Two-letter ISO codes for parent territories
* Comma-separated string of 2-letter ISO codes corresponding to PARENTS_3
*/
static const char* PARENTS_2 = "US,IN,CA,AU,MX,BR,RU,CN,";
/**
* @brief Territory enumeration values for parent territories
* Array mapping parent territory numbers (1-8) to their Territory enum values.
* Index 0 is TERRITORY_NONE, indices 1-8 are the 8 parent territories.
*/
static const enum Territory PARENT_NR[9] = {
TERRITORY_NONE, // 0 - no parent
TERRITORY_USA, // 1 - United States of America
TERRITORY_IND, // 2 - India
TERRITORY_CAN, // 3 - Canada
TERRITORY_AUS, // 4 - Australia
TERRITORY_MEX, // 5 - Mexico
TERRITORY_BRA, // 6 - Brazil
TERRITORY_RUS, // 7 - Russia
TERRITORY_CHN // 8 - China
};
/**
* @section base31_encoding Base-31 Encoding Character Set
* The mapcode system uses a base-31 alphabet for compact encoding.
* Character set is designed to avoid ambiguous characters and improve readability.
*/
/**
* @brief Base-31 encoding alphabet used for mapcode generation
*
* Character mapping:
* - Positions 0-9: Digits '0'-'9'
* - Positions 10-30: Consonants 'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'
* - Positions 31-33: Vowels 'A','E','U' (used for special purposes)
*
* Notable exclusions: 'I' and 'O' are excluded to avoid confusion with '1' and '0'
*/
static const char ENCODE_CHARS[34] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // Digits (0-9)
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', // Consonants (10-19)
'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', // Consonants (20-30)
'A', 'E', 'U' // Vowels (31-33)
};
/**
* @brief Convert ASCII character to base-31 value for mapcode decoding
* @param ch ASCII character to decode
* @return Base-31 value (0-30), or negative for special cases:
* -1: illegal character
* -2: vowel 'A' (position 31 in ENCODE_CHARS)
* -3: vowel 'E' (position 32 in ENCODE_CHARS)
* -4: vowel 'U' (position 33 in ENCODE_CHARS)
*
* Special handling: 'O'/'o' maps to '0', 'I'/'i' maps to '1' for user convenience.
* This allows users to type potentially confusing characters and still get correct results.
*/
static signed char decodeChar(const char ch) {
// Lookup table for base-31 value of ASCII character (negative for illegal characters)
// Special cases -2, -3, -4 for vowels; 'O' and 'I' interpreted as '0' and '1'.
static const signed char decode_chars[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 16
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 32
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 48
-1, -2, 10, 11, 12, -3, 13, 14, 15, 1, 16, 17, 18, 19, 20, 0, // 64
21, 22, 23, 24, 25, -4, 26, 27, 28, 29, 30, -1, -1, -1, -1, -1, // 80
-1, -2, 10, 11, 12, -3, 13, 14, 15, 1, 16, 17, 18, 19, 20, 0, // 96
21, 22, 23, 24, 25, -4, 26, 27, 28, 29, 30, -1, -1, -1, -1, -1, // 112
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 128
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 144
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 160
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 176
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 192
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 208
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 224
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 // 240
};
return decode_chars[(unsigned char)ch]; // ch can be negative, must be fit to range 0-255.
}
/**
* @brief Calculate the distance in meters between two coordinate points
* @param latDeg1 Latitude of first point in degrees (-90 to 90)
* @param lonDeg1 Longitude of first point in degrees (-180 to 180)
* @param latDeg2 Latitude of second point in degrees (-90 to 90)
* @param lonDeg2 Longitude of second point in degrees (-180 to 180)
* @return Distance between the two points in meters
*
* This function calculates the approximate distance between two points on Earth's surface
* using a simplified spherical model. The calculation:
* 1. Handles longitude wrapping around the 180°/-180° meridian
* 2. Uses cosine correction for longitude distance based on average latitude
* 3. Applies Pythagorean theorem to get final distance
*
* Note: This is an approximation suitable for mapcode purposes but not a precise
* geodetic distance calculation (which would require ellipsoid math).
*
* @public
*/
double distanceInMeters(double latDeg1, double lonDeg1, double latDeg2, double lonDeg2) {
double dx;
double dy;
double deltaLonDegrees;
double deltaLatDegrees;
int wrapped = lonDeg1 > lonDeg2;
ASSERT((-90.0 <= latDeg1) && (latDeg1 <= 90.0));
ASSERT((-90.0 <= latDeg2) && (latDeg2 <= 90.0));
if (wrapped) {
deltaLonDegrees = 360.0 - (lonDeg1 - lonDeg2);
}
else {
deltaLonDegrees = lonDeg2 - lonDeg1;
}
if (deltaLonDegrees > 180.0) {
deltaLonDegrees = 360.0 - deltaLonDegrees;
}
deltaLatDegrees = fabs(latDeg1 - latDeg2);
dy = deltaLatDegrees * METERS_PER_DEGREE_LAT;
dx = deltaLonDegrees * METERS_PER_DEGREE_LON * cos((latDeg1 + (latDeg2 - latDeg1) / 2.0) * MATH_PI / 180.0);
return sqrt(dx * dx + dy * dy);
}
/**
* @section precision_error_calculation Precision Error Calculation
* The mapcode system supports high-precision encoding with additional digits.
* Each extra digit reduces the maximum possible error by approximately a factor of 5.
*/
/**
* @brief Maximum error distances in meters for different precision levels
*
* This lookup table contains the maximum possible error (in meters) for each
* supported precision level. The values are empirically determined based on
* the mapcode grid system:
*
* Index 0: Base precision (no extra digits) - ~7.49m max error
* Index 1: 1 extra digit - ~1.39m max error
* Index 2: 2 extra digits - ~0.251m max error
* ... and so on up to MAX_PRECISION_DIGITS
*
* Each additional precision level reduces error by approximately 30^0.5 ≈ 5.48x
*/
static const double MAX_ERROR_IN_METERS[MAX_PRECISION_DIGITS + 1] = {
7.49, // 0 extra digits - base precision
1.39, // 1 extra digit
0.251, // 2 extra digits
0.0462, // 3 extra digits
0.00837, // 4 extra digits
0.00154, // 5 extra digits
0.000279, // 6 extra digits
0.0000514, // 7 extra digits
0.0000093 // 8 extra digits (maximum supported)
};
/**
* @brief Get the maximum possible error for a given precision level
* @param extraDigits Number of extra precision digits (0 to MAX_PRECISION_DIGITS)
* @return Maximum error in meters for this precision level, or 0.0 for invalid input
*
* This function returns the theoretical maximum error that can occur when encoding
* a coordinate at the specified precision level. The actual error is typically
* much smaller than this maximum value.
*
* @public
*/
double maxErrorInMeters(int extraDigits) {
ASSERT(extraDigits >= 0);
if ((extraDigits < 0) || (extraDigits > MAX_PRECISION_DIGITS)) {
return 0.0;
}
return MAX_ERROR_IN_METERS[extraDigits];
}
/**
* @section coordinate_structures Coordinate Representation Structures
* The mapcode system uses multiple coordinate representations for different purposes:
* - Point32: Integer microdegree coordinates (precise, efficient)
* - Point: Floating-point coordinates (flexible units depending on context)
*/
/**
* @brief Integer coordinate point in microdegrees
*
* This structure represents coordinates using 32-bit integers in microdegrees
* (millionths of a degree). This provides:
* - High precision without floating-point rounding errors
* - Efficient storage and comparison operations
* - Range: approximately ±2147 degrees (more than sufficient for Earth coordinates)
*/
typedef struct {
int latMicroDeg; // Latitude in microdegrees (±90,000,000 for ±90°)
int lonMicroDeg; // Longitude in microdegrees (±180,000,000 for ±180°)
} Point32;
/**
* @brief Floating-point coordinate point with flexible units
*
* This structure uses double-precision floating-point numbers.
* The units depend on context:
* - Sometimes degrees (for user-facing coordinates)
* - Sometimes fractions (for internal grid calculations)
* - Sometimes other units (for intermediate calculations)
*/
typedef struct {
double lat; // Latitude (units depend on usage context)
double lon; // Longitude (units depend on usage context)
} Point;
/**
* @brief Convert fraction coordinates to 32-bit microdegree coordinates
* @param p Point containing coordinates in fraction units
* @return Point32 with coordinates converted to microdegrees
*
* This function converts from the internal fraction coordinate system
* to microdegree integers. The conversion factors (810000, 3240000) are
* derived from the mapcode grid mathematics.
*/
static Point32 convertFractionsToCoord32(const Point* p) {
Point32 p32;
p32.latMicroDeg = (int)floor(p->lat / 810000); // Convert latitude fractions to microdegrees
p32.lonMicroDeg = (int)floor(p->lon / 3240000); // Convert longitude fractions to microdegrees
return p32;
}
/**
* @brief Convert fraction coordinates to degree coordinates
* @param p Point containing coordinates in fraction units
* @return Point with coordinates converted to degrees
*
* This function converts from the internal fraction coordinate system
* to standard degree coordinates. The large divisors (810000 * 1000000,
* 3240000 * 1000000) scale from fractions to degrees.
*/
static Point convertFractionsToDegrees(const Point* p) {
Point pd;
pd.lat = p->lat / (810000 * 1000000.0); // Convert latitude fractions to degrees
pd.lon = p->lon / (3240000 * 1000000.0); // Convert longitude fractions to degrees
return pd;
}
static const unsigned char DOUBLE_NAN[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F}; // NAN (Not a Number)
static const unsigned char DOUBLE_INF[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F}; // +Infinity
static const unsigned char DOUBLE_MIN_INF[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF}; // -Infinity
static enum MapcodeError
convertCoordsToMicrosAndFractions(Point32* coord32, int* fracLat, int* fracLon, double latDeg, double lonDeg) {
double frac;
ASSERT(coord32);
if (memcmp(&lonDeg, DOUBLE_NAN, 8) == 0 || memcmp(&lonDeg, DOUBLE_INF, 8) == 0 ||
memcmp(&lonDeg, DOUBLE_MIN_INF, 8) == 0 ||
memcmp(&latDeg, DOUBLE_NAN, 8) == 0) {
return ERR_BAD_COORDINATE;
}
if (latDeg < -90) {
latDeg = -90;
}
else if (latDeg > 90) {
latDeg = 90;
}
latDeg += 90; // lat now [0..180]
ASSERT((0.0 <= latDeg) && (latDeg <= 180.0));
latDeg *= (double)810000000000;
frac = floor(latDeg + 0.1);
coord32->latMicroDeg = (int)(frac / (double)810000);
if (fracLat) {
frac -= ((double)coord32->latMicroDeg * (double)810000);
*fracLat = (int)frac;
}
coord32->latMicroDeg -= 90000000;
lonDeg -= (360.0 * floor(lonDeg / 360)); // lon now in [0..360>
ASSERT((0.0 <= lonDeg) && (lonDeg < 360.0));
lonDeg *= (double)3240000000000;
frac = floor(lonDeg + 0.1);
coord32->lonMicroDeg = (int)(frac / (double)3240000);
if (fracLon) {
frac -= (double)coord32->lonMicroDeg * (double)3240000;
*fracLon = (int)frac;
}
if (coord32->lonMicroDeg >= 180000000) {
coord32->lonMicroDeg -= 360000000;
}
return ERR_OK;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// TerritoryBoundary (specified in microDegrees)
//
///////////////////////////////////////////////////////////////////////////////////////////////
// returns nonzero if x in the range minx...maxx
static int isInRange(int lonMicroDeg, const int minLonMicroDeg, const int maxLonMicroDeg) {
if (minLonMicroDeg <= lonMicroDeg && lonMicroDeg < maxLonMicroDeg) {
return 1;
}
if (lonMicroDeg < minLonMicroDeg) {
lonMicroDeg += 360000000;
}
else {
lonMicroDeg -= 360000000;
} // 1.32 fix FIJI edge case
if (minLonMicroDeg <= lonMicroDeg && lonMicroDeg < maxLonMicroDeg) {
return 1;
}
return 0;
}
// returns true iff given coordinate "coord32" fits inside given TerritoryBoundary
static int fitsInsideBoundaries(const Point32* coord32, const TerritoryBoundary* b) {
ASSERT(coord32);
ASSERT(b);
return (b->miny <= coord32->latMicroDeg &&
coord32->latMicroDeg < b->maxy &&
isInRange(coord32->lonMicroDeg, b->minx, b->maxx));
}
// set target TerritoryBoundary to a source extended with deltalat, deltaLon (in microDegrees)
static TerritoryBoundary* getExtendedBoundaries(TerritoryBoundary* target, const TerritoryBoundary* source,
const int deltaLatMicroDeg, const int deltaLonMicroDeg) {
ASSERT(target);
ASSERT(source);
target->miny = source->miny - deltaLatMicroDeg;
target->minx = source->minx - deltaLonMicroDeg;
target->maxy = source->maxy + deltaLatMicroDeg;
target->maxx = source->maxx + deltaLonMicroDeg;
return target;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// MapcodeZone
//
///////////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
// latitudes in "810 billionths", range [-729 E11 .. +720 E11), is well within (-2^47 ... +2^47)
double fminy;
double fmaxy;
// latitudes in "3240 billionths", range [-2916 E13 .. +2916 E13), is well within (-2^49 ... +2^49)
double fminx;
double fmaxx;
} MapcodeZone;
static void setFromFractions(MapcodeZone* z,
const double y, const double x,
const double yDelta, const double xDelta) {
ASSERT(z);
z->fminx = x;
z->fmaxx = x + xDelta;
if (yDelta < 0) {
z->fminy = y + 1 + yDelta; // y+yDelta can NOT be represented
z->fmaxy = y + 1; // y CAN be represented
}
else {
z->fminy = y;
z->fmaxy = y + yDelta;
}
}
static int isEmpty(const MapcodeZone* z) {
ASSERT(z);
return ((z->fmaxx <= z->fminx) || (z->fmaxy <= z->fminy));
}
static Point getMidPointFractions(const MapcodeZone* z) {
Point p;
ASSERT(z);
p.lon = floor((z->fminx + z->fmaxx) / 2);
p.lat = floor((z->fminy + z->fmaxy) / 2);
return p;
}
static void zoneCopyFrom(MapcodeZone* target, const MapcodeZone* source) {
ASSERT(target);
ASSERT(source);
target->fminy = source->fminy;
target->fmaxy = source->fmaxy;
target->fminx = source->fminx;
target->fmaxx = source->fmaxx;
}
// determine the non-empty intersection zone z between a given zone and the boundary of territory rectangle m.
// returns nonzero in case such a zone exists
static int restrictZoneTo(MapcodeZone* z, const MapcodeZone* zone, const TerritoryBoundary* b) {
ASSERT(z);
ASSERT(zone);
ASSERT(b);
z->fminy = zone->fminy;
z->fmaxy = zone->fmaxy;
if (z->fminy < b->miny * MICROLAT_TO_FRACTIONS_FACTOR) {
z->fminy = b->miny * MICROLAT_TO_FRACTIONS_FACTOR;
}
if (z->fmaxy > b->maxy * MICROLAT_TO_FRACTIONS_FACTOR) {
z->fmaxy = b->maxy * MICROLAT_TO_FRACTIONS_FACTOR;
}
if (z->fminy < z->fmaxy) {
double bminx = b->minx * MICROLON_TO_FRACTIONS_FACTOR;
double bmaxx = b->maxx * MICROLON_TO_FRACTIONS_FACTOR;
z->fminx = zone->fminx;
z->fmaxx = zone->fmaxx;
if (bmaxx < 0 && z->fminx > 0) {
bminx += (360000000 * MICROLON_TO_FRACTIONS_FACTOR);
bmaxx += (360000000 * MICROLON_TO_FRACTIONS_FACTOR);
}
else if (bminx > 0 && z->fmaxx < 0) {
bminx -= (360000000 * MICROLON_TO_FRACTIONS_FACTOR);
bmaxx -= (360000000 * MICROLON_TO_FRACTIONS_FACTOR);
}
if (z->fminx < bminx) {
z->fminx = bminx;
}
if (z->fmaxx > bmaxx) {
z->fmaxx = bmaxx;
}
return (z->fminx < z->fmaxx);
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// COPY ROUTINES
//
///////////////////////////////////////////////////////////////////////////////////////////////
// PRIVATE - copy characters into targetString, limited to its size
static char* lengthCopy(char* targetString, const char* sourceString, int nrCharacters, int targetSize) {
if (nrCharacters >= targetSize) {
nrCharacters = targetSize - 1;
}
memcpy(targetString, sourceString, (size_t)nrCharacters);
targetString[nrCharacters] = 0;
return targetString;
}
// PRIVATE - copy as much of sourceString as will fit; returns targetString
static char* safeCopy(char* targetString, const char* sourceString, const int targetSize) {
int sourceLength = (int)strlen(sourceString);
return lengthCopy(targetString, sourceString, sourceLength, targetSize);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Data access
//
///////////////////////////////////////////////////////////////////////////////////////////////
/*** low-level data access ***/
static int firstRec(const enum Territory ccode) {
ASSERT((_TERRITORY_MIN < ccode) && (ccode < _TERRITORY_MAX));
return DATA_START[INDEX_OF_TERRITORY(ccode)];
}
static int lastRec(const enum Territory ccode) {
ASSERT((_TERRITORY_MIN < ccode) && (ccode < _TERRITORY_MAX));
return DATA_START[INDEX_OF_TERRITORY(ccode) + 1] - 1;
}
// returns parent of ccode (or TERRITORY_NONE)
static enum Territory parentTerritoryOf(const enum Territory ccode) {
if (ccode <= _TERRITORY_MIN || ccode >= _TERRITORY_MAX) {
return TERRITORY_NONE;
}
return PARENT_NR[(int)PARENT_LETTER[INDEX_OF_TERRITORY(ccode)]];
}
static int coDex(const int m) {
int c = TERRITORY_BOUNDARIES[m].flags & 31;
ASSERT((0 <= m) && (m <= MAPCODE_BOUNDARY_MAX));
return 10 * (c / 5) + ((c % 5) + 1);
}
static int xDivider4(const int miny, const int maxy) {
// 360 * cos(microdegrees>>19)
static const int xdivider19[172] = {
360, 360, 360, 360, 360, 360, 361, 361, 361, 361,
362, 362, 362, 363, 363, 363, 364, 364, 365, 366,
366, 367, 367, 368, 369, 370, 370, 371, 372, 373,
374, 375, 376, 377, 378, 379, 380, 382, 383, 384,
386, 387, 388, 390, 391, 393, 394, 396, 398, 399,
401, 403, 405, 407, 409, 411, 413, 415, 417, 420,
422, 424, 427, 429, 432, 435, 437, 440, 443, 446,
449, 452, 455, 459, 462, 465, 469, 473, 476, 480,
484, 488, 492, 496, 501, 505, 510, 515, 520, 525,
530, 535, 540, 546, 552, 558, 564, 570, 577, 583,
590, 598, 605, 612, 620, 628, 637, 645, 654, 664,
673, 683, 693, 704, 715, 726, 738, 751, 763, 777,
791, 805, 820, 836, 852, 869, 887, 906, 925, 946,
968, 990, 1014, 1039, 1066, 1094, 1123, 1154, 1187, 1223,
1260, 1300, 1343, 1389, 1438, 1490, 1547, 1609, 1676, 1749,
1828, 1916, 2012, 2118, 2237, 2370, 2521, 2691, 2887, 3114,
3380, 3696, 4077, 4547, 5139, 5910, 6952, 8443, 10747, 14784,
23681, 59485
};
if (miny >= 0) {
// both above equator? then miny is closest
return xdivider19[(miny) >> 19];
}
if (maxy >= 0) {
// opposite sides? then equator is worst
return xdivider19[0];
}
return xdivider19[(-maxy) >> 19]; // both negative, so maxy is closest to equator
}
/*** mid-level data access ***/
// returns true iff ccode is a subdivision of some other country
static int isSubdivision(const enum Territory ccode) {
return parentTerritoryOf(ccode) != TERRITORY_NONE;
}
// find first territory rectangle of the same type as m
static int firstNamelessRecord(const int m, const int firstcode) {
int i = m;
const int codexm = coDex(m);
ASSERT((0 <= m) && (m <= MAPCODE_BOUNDARY_MAX));
ASSERT((0 <= firstcode) && (firstcode <= MAPCODE_BOUNDARY_MAX));
while (i >= firstcode && coDex(i) == codexm && IS_NAMELESS(i)) {
i--;
}
return (i + 1);
}
// count all territory rectangles of the same type as m
static int countNamelessRecords(const int m, const int firstcode) {
const int first = firstNamelessRecord(m, firstcode);
const int codexm = coDex(m);
int last = m;
ASSERT((0 <= m) && (m <= MAPCODE_BOUNDARY_MAX));
ASSERT((0 <= firstcode) && (firstcode <= MAPCODE_BOUNDARY_MAX));
while (coDex(last) == codexm) {
last++;
}
ASSERT((0 <= last) && (last <= MAPCODE_BOUNDARY_MAX));
ASSERT(last >= first);
return (last - first);
}
static int isNearBorderOf(const Point32* coord32, const TerritoryBoundary* b) {
int xdiv8 = xDivider4(b->miny, b->maxy) / 4; // should be /8 but there's some extra margin
TerritoryBoundary tmp;
ASSERT(coord32);
ASSERT(b);
return (fitsInsideBoundaries(coord32, getExtendedBoundaries(&tmp, b, +60, +xdiv8)) &&
(!fitsInsideBoundaries(coord32, getExtendedBoundaries(&tmp, b, -60, -xdiv8))));
}
static void makeUppercase(char* s) {
ASSERT(s);
while (*s) {
*s = (char)toupper(*s);
s++;
}
}
// returns 1 - 8, or negative if error
static int getParentNumber(const char* s, const int len) {
const char* p = ((len == 2) ? PARENTS_2 : PARENTS_3);
const char* f;
char country[4];
ASSERT(s[0] && s[1]);
ASSERT((2 <= len) && (len <= 3));
ASSERT(s && ((int) strlen(s) >= len));
lengthCopy(country, s, len, 4);
makeUppercase(country);
f = strstr(p, country);
if (!f) {
return -1;
}
return 1 + (int)((f - p) / (len + 1));
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// MAPCODE ALL-DIGIT PACKING/UNPACKING
//
///////////////////////////////////////////////////////////////////////////////////////////////
static void repackIfAllDigits(char* input, const int aonly) {
char* s = input;
int alldigits = 1; // assume all digits
char* e;
char* dotpos = NULL;
ASSERT(input);
for (e = s; *e != 0 && *e != '-'; e++) {
if (*e < '0' || *e > '9') {
if (*e == '.' && !dotpos) {
dotpos = e;
}
else {
alldigits = 0;
break;
}
}
}
e--;
s = e - 1;
if (alldigits && dotpos &&
s > dotpos) // e is last char, s is one before, both are beyond dot, all characters are digits
{
if (aonly) // v1.50 - encode only using the letter A
{
const int v = ((*input) - '0') * 100 + ((*s) - '0') * 10 + ((*e) - '0');
*input = 'A';
*s = ENCODE_CHARS[v / 32];
*e = ENCODE_CHARS[v % 32];
}
else // encode using A,E,U
{
const int v = ((*s) - '0') * 10 + ((*e) - '0');
*s = ENCODE_CHARS[(v / 34) + 31];
*e = ENCODE_CHARS[v % 34];
}
}
}
// rewrite all-digit codes
// returns 1 if unpacked, 0 if left unchanged, negative if unchanged and an error was detected
static int unpackIfAllDigits(char* input) {
char* s = input;
char* dotpos = NULL;
const int aonly = ((*s == 'A') || (*s == 'a'));
if (aonly) {
s++;
} // v1.50
for (; *s != 0 && s[2] != 0 && s[2] != '-'; s++) {
if (*s == '-') {
break;
}
else if (*s == '.' && !dotpos) {
dotpos = s;
}
else if ((decodeChar(*s) < 0) || (decodeChar(*s) > 9)) {
return 0;
} // nondigit, so stop
}
if (dotpos) {
if (aonly) // v1.50 encoded only with A's
{
const int v = (((s[0] == 'A') || (s[0] == 'a')) ? 31 : decodeChar(s[0])) * 32 +
(((s[1] == 'A') || (s[1] == 'a')) ? 31 : decodeChar(s[1]));
*input = (char)('0' + (v / 100));
s[0] = (char)('0' + ((v / 10) % 10));
s[1] = (char)('0' + (v % 10));
return 1;
} // v1.50
if ((*s == 'a') || (*s == 'e') || (*s == 'u') ||
(*s == 'A') || (*s == 'E') || (*s == 'U')) {
char* e = s + 1; // s is vowel, e is lastchar
int v = 0;
if (*s == 'e' || *s == 'E') {
v = 34;
}
else if (*s == 'u' || *s == 'U') {
v = 68;
}
if ((*e == 'a') || (*e == 'A')) {
v += 31;
}
else if ((*e == 'e') || (*e == 'E')) {
v += 32;
}
else if ((*e == 'u') || (*e == 'U')) {
v += 33;
}
else if (decodeChar(*e) < 0) {
return (int)ERR_INVALID_CHARACTER;
}
else {
v += decodeChar(*e);
}
if (v < 100) {
*s = ENCODE_CHARS[(unsigned int)v / 10];
*e = ENCODE_CHARS[(unsigned int)v % 10];
}