Skip to content
GitHub

Reference

Places API

Every public function, method, type and error of @mdgascar/places and mdgascar/malagasy-address.

Everything the two packages export, with the same behaviour and the same error codes in JavaScript and PHP. The data is the OCHA COD-AB for Madagascar (CC BY-IGO).

A place code starts with MG and the code of a place starts with the code of its parent. The four levels, from the largest to the smallest:

Level Code Example Places
region MG + 2 digits MG11 24
district region + 3 digits MG11102 120
commune district + 3 digits MG11102430 1 645
fokontany commune + 3 digits MG11102430001 17 465

Every function that takes a code reads it the same way: letter case and spaces around it are free (' mg11 ' is MG11), and text longer than the length limit is rejected before it is read.

A rejected input throws MalagasyAddressError in JavaScript and MalagasyAddressException in PHP. Both carry the same code.

Code When
INVALID_TYPE A value is not of the accepted type: a code that is not text, a latitude or longitude that is not a finite number.
INVALID_FORMAT Text cannot be read: a badly written code, a search text that is too short or too long, an unknown level or search option.
UNKNOWN_PLACE A well written code that is not in the list, or no place of the level is loaded.
OUT_OF_RANGE A latitude outside -90 to 90, a longitude outside -180 to 180, or a point outside Madagascar.

MalagasyAddressError extends Error, has the read-only code (an ErrorCode) and name 'MalagasyAddressError'.

Export Does
describeError(error, locale?) The end-user message for a code or an error, in 'en' (default) or 'fr'.
ErrorCode 'INVALID_TYPE' | 'INVALID_FORMAT' | 'UNKNOWN_PLACE' | 'OUT_OF_RANGE'.
MessageLocale 'en' | 'fr'.
SafeParseResult<T> { success: true, data: T } | { success: false, error: MalagasyAddressError }.
SPEC_VERSION The version of the spec the package implements.
import { describeError, findPlace } from '@mdgascar/places';
try {
findPlace('MG99');
} catch (error) {
describeError(error, 'fr'); // 'Ce lieu ne figure pas dans la liste des divisions de Madagascar.'
}
Type Shape
PlaceLevel 'region' | 'district' | 'commune' | 'fokontany'
Place { code, level, name }
PlaceWithParents A Place and parents: the places above it, from the region down to the direct parent.
PlaceLocation { latitude, longitude, areaKm2 }: degrees (north and east positive, 5 decimals) and km2 (2 decimals).
SearchOptions { level?: PlaceLevel, within?: string }
PlaceBook The functions below with the loaded fokontany: findPlace, safeFindPlace, tryFindPlace, listPlaces, searchPlaces, formatPlace, locatePlace, distanceBetween, nearestPlace.
LoadPlacesOptions { read: BlobReader, regions?: readonly string[] }
BlobReader (path: string) => Promise<RegionBlob | GeoBlob>
RegionBlob fokontany/<region>.json: the fokontany of each commune, by commune code.
FokontanyOfCommune The names numbered 001, 002, … as a list, or a map from number to name when the numbers are not consecutive.
GeoBlob geo/<region>.json: [latitude, longitude, areaKm2] of each fokontany, by code.
Function Returns Throws
findPlace(code: string) PlaceWithParents INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
safeFindPlace(code: unknown) SafeParseResult<PlaceWithParents> never
tryFindPlace(code: unknown) PlaceWithParents | undefined never
findPlace('MG11102').name; // 'Antananarivo Avaradrano'
findPlace('MG11102').parents[0]?.name; // 'Analamanga'
tryFindPlace('MG99'); // undefined
safeFindPlace('MG99'); // { success: false, error }

The place and the places that contain it. The three forms read the code the same way. Only find has safe and try forms: the other functions throw.

Function Returns Throws
listPlaces(parentCode?: string | null) Place[] INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
listPlaces().length; // 24, the regions
listPlaces('MG11')[0]?.level; // 'district'

The places directly below a place, in code order; no code gives the regions. A fokontany has none, so its list is empty.

Function Returns Throws
searchPlaces(text: string, options?: SearchOptions) PlaceWithParents[] INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
searchPlaces('avaradrano', { level: 'district' })[0]?.code; // 'MG11102'
searchPlaces('ambohi', { within: 'MG11102' })[0]?.name; // a place below that district

Case, accents and punctuation are ignored, and a place matches when its name contains the text. Results are ranked: the exact name, then names that start with the text, then names with a word that starts with it, then the rest; within a rank the shorter name first, then the lower code. At most 50 places are returned, and nothing found is an empty list, not an error.

Option Keeps Notes
level One level. An unknown level is INVALID_FORMAT.
within The places below a code. A place is not below itself. A badly written code is INVALID_FORMAT, an unknown one UNKNOWN_PLACE.

The two options combine. JavaScript rejects an unknown option key with INVALID_FORMAT. The text must be at least 2 characters once folded.

Function Returns Throws
formatPlace(code: string) string INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
formatPlace('MG11102'); // 'Antananarivo Avaradrano, Analamanga'

The name, then the name of each parent up to the region, separated by commas.

Function Returns Throws
locatePlace(code: string) PlaceLocation INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
locatePlace('MG11').areaKm2; // the area of Analamanga in km2

The point the COD-AB gives for the place and its area. The point is a reference point of the place, not a proof that the place contains it.

Function Returns Throws
distanceBetween(codeA: string, codeB: string) number (km) INVALID_TYPE, INVALID_FORMAT, UNKNOWN_PLACE
distanceBetween('MG11', 'MG12'); // the km between the two regions

The great circle (haversine) distance between the two points on a sphere of radius 6371.0088 km, rounded to metres. The same place is 0. Both codes are checked.

Function Returns Throws
nearestPlace(latitude: number, longitude: number, level: PlaceLevel) PlaceWithParents INVALID_TYPE, INVALID_FORMAT, OUT_OF_RANGE, UNKNOWN_PLACE
nearestPlace(-18.9, 47.52, 'region').name; // 'Analamanga'

The place of the level whose point is nearest to the given point; a tie goes to the lower code. It answers “nearest point”, not “contains”: near a boundary the place that contains the point can be another one. The checks run in this order: latitude and longitude finite numbers and the level text (INVALID_TYPE), a known level (INVALID_FORMAT), latitude and longitude in range and the point inside the box around Madagascar, latitude -26 to -11 and longitude 43 to 51 (OUT_OF_RANGE). In JavaScript, UNKNOWN_PLACE means no place of that level is loaded, which only happens for fokontany before loadPlaces. You can check the box on the map.

The regions, districts and communes are part of the package. The fokontany are raw files in data/, two per region, that you load when you need them. PHP has them built in, so none of this exists in PHP.

Export Returns Throws
loadPlaces({ read, regions? }) Promise<PlaceBook> INVALID_FORMAT (a region code that is not a region, or a file that is not valid), UNKNOWN_PLACE
fetchBlobReader(baseUrl) BlobReader Error when a file cannot be fetched, INVALID_FORMAT when it is not JSON

read gets one file by its path, fokontany/MG11.json or geo/MG11.json, and returns the parsed JSON. regions lists the region codes to load, each read once; without it all 24 regions load. Each fokontany of the names files must have a point in the geo file, or the load fails with INVALID_FORMAT.

import { fetchBlobReader, loadPlaces } from '@mdgascar/places';
const places = await loadPlaces({
read: fetchBlobReader('https://example.com/malagasy-data/'),
regions: ['MG11'],
});
places.findPlace('MG11102430001').name; // 'Ankadinandriana'
places.locatePlace('MG11102430001').areaKm2; // the area of that fokontany in km2