Skip to content


Switch branches/tags

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

Mapcode Library for C/C++

Codacy Badge License

Copyright (C) 2014-2017 Stichting Mapcode Foundation (

Online documentation:

Latest stable release:

The C/C++ Library: mapcodelib/

The directory 'mapcodelib' contains the files:

  mapcoder.h                    <-- Header file with method prototypes and defines for caller.
  mapcoder.c                    <-- Implementation of mapcode routines.
  internal_*.h                  <-- Internal implementataion details for library.

  mapcode_alphabets.h           <-- Enumeration of supported alphabets (or scripts).
  mapcode_territories.h         <-- Enumeration of supported territories.
  mapcode_legacy.h              <-- Courtesy support for legacy calls, may be deprecated in future.

Together these provide routine to encode/decode Mapcodes.

Documentation, including example snippets of C source code, can be found in

  mapcode_library_c.pdf         <-- PDF format.
  mapcode_library_c.docx        <-- Microsoft Word format.

A unit test can be found in the test subdirectory. Compile and run unittest.c to see if the library performs as expected:

cd mapcodelib
gcc -O -c mapcoder.c
cd ../test
gcc -O unittest.c -lm -lpthread -o unittest ../mapcodelib/mapcoder.o

Check the in directory test for more information.

Also see for background and reference materials.

A Real-Life Example, The 'mapcode' Codec Tool: utility/

The directory 'utility' contains a Mapcode encoding/decoding utility, as an example of how to use the library.

To build the original Mapcode tool, execute:

cd mapcodelib
gcc -O -c mapcoder.c
cd ../utility
gcc -O mapcode.cpp -o mapcode ../mapcodelib/mapcoder.o

For help, simply execute the binary file 'mapcode' without no arguments. This tool provides a rather extensive command-line interface to encode and decode Mapcodes.

This produces the following help text:

MAPCODE (version 2.5.5)
Copyright (C) 2014-2017 Stichting Mapcode Foundation

    mapcode [-d| --decode] <default-territory> <mapcode> [<mapcode> ...]

       Decode a mapcode to a lat/lon. The default territory code is used if
       the mapcode is a shorthand local code

    mapcode [-e[0-8] | --encode[0-8]] <lat:-90..90> <lon:-180..180> [territory]>

       Encode a lat/lon to a mapcode. If the territory code is specified, the
       encoding will only succeeed if the lat/lon is located in the territory.
       You can specify the number of additional digits, 0, 1 or 2 (default 0)
       for high-precision mapcodes.

    mapcode [-t | --territories]

       Create a full set of territories in CSV format.

    mapcode [-a | --alphabets]

       Create a full set of alphabet tests in CSV format.

    mapcode [-b[XYZ] | --boundaries[XYZ]] [<extraDigits>]
    mapcode [-g[XYZ] | --grid[XYZ]]   <nrOfPoints> [<extraDigits>]
    mapcode [-r[XYZ] | --random[XYZ]] <nrOfPoints> [<extraDigits>] [<seed>]

       Create a test set of lat/lon pairs based on the mapcode boundaries database
       as a fixed 3D grid or random uniformly distributed set of lat/lons with their
       (x, y, z) coordinates and all mapcode aliases.

       <extraDigits>: 0-8; specifies additional accuracy, use 0 for standard.
       <seed> is an optional random seed, use 0 for arbitrary>.
       (You may wish to specify a specific seed to regenerate test cases).

       The output format is:
           <number-of-aliases> <lat-deg> <lon-deg> [<x> <y> <z>]
           <territory> <mapcode>      (repeated 'number-of-aliases' times)
                                      (empty lines and next record)
           number-of-aliases : >= 1
           lat-deg, lon-deg  : [-90..90], [-180..180]
           x, y, z           : [-1..1]

       The lat/lon pairs will be distributed over the 3D surface of the Earth
       and the (x, y, z) coordinates are placed on a sphere with radius 1.
       The (x, y, z) coordinates are primarily meant for visualization of the data set.

       mapcode -g    100 : produces a grid of 100 points as lat/lon pairs
       mapcode -gXYZ 100 : produces a grid of 100 points as (x, y, z) sphere coordinates)

       Notes on the use of stdout and stderr:
       stdout: used for outputting 3D Point data; stderr: used for statistics.
       You can redirect stdout to a destination file, while stderr will show progress.

       The result code is 0 when no error occurred, 1 if an input error occurred and 2
       if an internal error occurred.

Compile Options for Microsoft Visual C++

If you use Microsoft Visual C++, you may need to add the following compiler directives to your build:


Reducing the Footprint of the Mapcode Library

The Mapcode C/C++ Library has includes a number of fixed data tables, which increase its footprint. You may not require all of this data, so we've added some options for you to be able to reduce its footprint, for example for embedded applications.

You can specify the define MAPCODE_NO_SUPPORT_ALL_LANGUAGES to disable support for territory names in all languages.

Note that English names are always supported and it's also always possible to get territory names in their locale language.

To add individual support support for other languages (of all territory names), use:

-DMAPCODE_NO_SUPPORT_ALL_LANGUAGES   // If not defined, ALL languages are available.
-DMAPCODE_SUPPORT_LANGUAGE_AF        // Add the languages you need. The names are the
-DMAPCODE_SUPPORT_LANGUAGE_AR        // ISO 3166-2 character codes.

The list of support languages may grow over time.

Using the C Library in an Xcode iOS Swift project

You can use this C library in an iOS application, built with Swift in Xcode, fairly easily. All you need to do is:

First, copy the directory mapcodelib to the source directory of your iOS application.

Then, add a text file called module.modulemap in the directory mapcodelib to export all symbols from the C library to Swift (note that #defines are not exported):

module mapcodelib [system][extern_c]{
    header "mapcode_alphabets.h"
    header "mapcode_territories.h"
    header "mapcoder.h"
    export *

Now, you can access the C library methods like this in a Swift project:

// Example of decoding a full mapcode to a lat/lon:
let territory = getTerritoryCode(context, TERRITORY_NONE)
var lat: Double = 0.0
var lon: Double = 0.0
let mapcodeError = decodeMapcodeToLatLonUtf8(&lat, &lon, fullMapcode, territory, nil)
if mapcodeError == ERR_OK {
    // Use the decoded lat and lon.
} else {
    // Something went wrong decoding the full mapcode string.

Or encode a latitude, longitude pair to a set of Mapcodes like this:

let buffer = UnsafeMutablePointer<Int8>.allocate(capacity: Int(_MAX_MAPCODE_RESULT_ASCII_LEN))
buffer.initialize(to: 0, count: Int(_MAX_MAPCODE_RESULT_ASCII_LEN))
var total: Int32 = 0;
var i: Int32 = 0
repeat {
    total = encodeLatLonToSelectedMapcode(buffer, lat, lon, TERRITORY_NONE, 0, i)
    if (total > 0) {
        let mapcode = String.init(cString: buffer);
    i = i + 1
} while (i < total)

Or get a territory name like this:

let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: Int(MAX_TERRITORY_FULLNAME_UTF8_LEN + 1))
buffer.initialize(to: 0, count: Int(_MAX_TERRITORY_FULLNAME_UTF8_LEN + 1))

// Get alpha code.
getTerritoryIsoName(buffer, TERRITORY_NLD, 0)
let alphaCode = String.init(cString: buffer)

// Get full name.
getFullTerritoryNameEnglish(buffer, TERRITORY_NLD, 0)
let fullName = String.init(cString: buffer)

Release Notes

2.5.4 - 2.5.5

  • Added encodeLatLonToSelectedMapcode as a convenience for languages that use the C library, but have difficulties dealing with multi-dimensional arrays (like Swift).


  • Cleaned up code after running Codacy code reviews.

  • Fixed copyright message.


  • Added unit test for floating point error with code "40822.schol".

  • Added locale support.

  • Added many languages.

  • Hardened unit tests.


  • Updated unit test to compile with plain C and added some test cases.


  • Added support for getting territory names in English and local alphabets.

  • Added much improved unit test scripts to run gprof, valgrind, the CLang address sanitize and compare the output of the new library with and older version.


  • Renamed .h files to internal_*.h unless they are relevant to the interface.

  • Turned territories, alphabets and error codes into enums.

  • Split off legacy stuff into mapcode_legacy.h.

  • Added convertUtf8ToUtf16, convertUtf16ToUtf8, recognizeAlphabetUtf8, recogniseAlphabetUtf16.


  • Added scripts for Korean (Choson'gul / Hangul), Burmese, Khmer, Sinhalese, Thaana (Maldivan), Chinese (Zhuyin, Bopomofo), Tifinagh (Berber), Tamil, Amharic, Telugu, Odia, Kannada, Gujarati.

  • Renamed constants to more correct terms (Malay to Malayalam, Hindi to Devanagari).

  • Added getAlphabetsForTerritory(t), returning the most commonly used alphabets for territory t.

  • Improved some characters for Arabic and Devanagari.

  • Fixed Bengali to also support Assamese.

  • Improved readability of implementation.

  • Added conditional define option for unittest: NO_POSIX_THREADS. Add -DNO_POSIX_THREADS to your compiler command-line to not use pthreads.h, for example, on MSVC platforms.

  • Added conditional define option library: NO_FAST_ENCODE. Add -DNO_FAST_ENCODE to your compiler command-line to not use the fast encoding (default is to use fast encoding). Using fast encoding speeds up de encoding by a factor of 2. For normal use, there is no reason not to use fast encoding.

  • Added parseMapcodeString to get individual mapcode elements, like the territory code, the 'proper' mapcode (without the territory and precision extension) and the precision extension parsed from a (user) input string.

  • Additional bug fixes.


  • Minor fixes to prevent compiler warnings.

  • Minor fixes to prevent multiple inclusion of .h files.

  • Minor data fix for Gansu Province, China (mountain range extending further west).


  • Arabic script added.

  • Tibetan script changed so all characters can be easily typed on a computer keyboard.

  • Greek, Hebrew and Arabic, the scripts that have (implied) vowels in mapcode sequences, have been extended with ABJAD conversion, to prevent more than two consecutive non-digits from occurring. (As a result, mapcodes in Greek, Arab and Hebrew scripts are now often one character longer than in the roman script.)


  • Removed minor warnings from CLion inspections.


  • Solved 1-microdegree gap in a few spots on Earth, noticable now extreme precision is possible.


  • Added stricter unit tests.


  • Added maxErrorInMetersz to API.

  • Moved recode logic into decoder.

  • Adjusted unit test.


  • Added useful routine DistanceInMeters to API.


  • Rewrote fraction floating points to integer arithmetic.


  • Added unittest/ which can be compiled and executed to check if the mapcode library performs as expected.


  • Fixes floating point inaccuracy (prevent encode(decode(M)) != M).


  • Added #define FAST_ALPHA for faster alphacode string recognition.

  • Added point structs to source.

  • Cleaned up source.

  • Cleaned up source.

  • Cleaned up source, removed legacy code.

  • Renamed dividemaps.h to mapcode_fast_encode.h.

  • Improved convertToRoman and convertToAlphabet to trim and skip leading territory.

  • Rolled back 2.0.2 fix for letters "i" and "o" in Hindi, Bengali, Tibetan and Gurmukhi.


  • Speed-up of encoding (4 times faster than 2.0.1).

  • Added optional mapcode_countrynames.h (with the English short names, formal names, and name variants of all territories) and mapcode_countrynames_short.h (with only the short English names and name variants.

  • Stricter processing of high-precision letters (now fails on illegal high-precision letters, which includes the letter Z).

  • Fix for letters "i" and "o" in Hindi, Bengali, Tibetan and Gurmukhi;

  • Fix for some unrecognized aliases in convertTerritoryIsoNameToCode().


  • Removed compiler warnings.


  • Support for high-precision mapcodes, with up to 8 character extensions (up to 10 micron accuracy).

  • Fixes to the data rectangles (primarily intended for ISO proposal), see Word document for details.


  • Bug fix for state IN-DD (in India).

  • If the executable name contains debug, the self checking mechanism is activated. Note, however, that this feature is under construction and produces false negative for certain decodes.


  • Major release. This version is not backwards compatible with mapcode 1.4x: is has dropped support for Antartica AT0-8 codes and has a changed (improved) way of dealing with the Greek alphabet.

  • Added 22-chararcter post-processing of all-digit mapcodes for the Greek alphabet.

  • Retired legacy aliases EAZ and SKM, AU-QL, AU-TS, AU-NI and AU-JB.

  • Retired legacy Antarctica claims AT0 through AT8.


  • Bugfix for utility/mapcode utility (-d option was case sensitive).


  • Added the India state Telangana (IN-TG), until 2014 a region in Adhra Pradesh.

  • Fixed a problem with the extraDigits parameter of the utility/mapcode utility (maximum digits is 2, not 3).


  • Added extraDigits parameter to allow high-precision mapcodes to be generated by the utility/mapcode utility.


  • Fix to not remove valid results just across the edge of a territory.

  • Improved interface readability and renamed methods to more readable forms.


  • Added encodeLatLonToSingleMapcode()

  • Fixed 1.29 so no country-wide alternative is produced in edge cases; prevent FIJI failing to decode at exactly 180 degrees.


  • Added compareWithMapcodeFormat().


  • IUpdated the documentation and extended it with examples and suggestions.


  • Also generate country-wide alternative mapcodes for states.


  • Bug fix for the needless generation of 7-letter alternatives to short mapcodes in large states in India.


  • Improved (faster) implementation of the function isInArea.


  • Added alias OD ("Odisha") for indian state OR ("Orissa").


  • Initial release to the public domain.


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

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.


Development of the C/C++ version of the Mapcode Library is kindly sponsored by JetBrains.