Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-02: janas-maps - roads and places as an MCP service (routes, public transport, what is near, addresses), tried in janas-chat

camaurid6b2cf29252b
diff --git a/ChangeLog.md b/ChangeLog.md
index d96c593..4fc6271 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,13 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-02] - janas-maps: roads and places
+
+- **janas-maps**, roads and places as an MCP service, from OpenStreetMap's data through free services with no key: a route by car, bike or on foot between two places or through a third, avoiding tolls, motorways or ferries when asked, with its length, time without traffic, main roads, up to two other ways, the way step by step in the computer's language and a link to the map (`maps_route`: Valhalla on FOSSGIS' servers, OSRM's route without steps when Valhalla does not answer); journeys by public transport leaving or arriving at a time, leg by leg (`maps_transit`: Transitous, over the operators' open timetables); the places of a kind around a place, nearest first, from a list of twenty kinds (`maps_nearby`: Overpass); where a place or an address is (`maps_find`: Nominatim, Photon when it does not answer). Every answer is data with a layout: the user sees the steps and the journeys, the model reads a brief. `janas-chat` starts it by itself; [docs/services/maps.md](docs/services/maps.md).
+- **The sources' rules are kept**: a User-Agent naming the program, at most one request a second to each server (`janas-maps` waits between two), answers kept a while, every server's address changeable (`JANAS_VALHALLA_URL` and the like), OpenStreetMap's attribution in every answer.
+- **What could go wrong, found and mended on the way**: a town named alone ("Trapani") is the municipality's boundary in Nominatim, whose point lies in the fields 25 km from the town, and a journey by bus from there took thirteen hours; the town's own point is taken now. OSRM's server knows Europe only and put New York on the nearest European road, a route of 3,556 km; a place that far from a road is now said to be unreachable.
+- **Tried in `janas-chat` with Qwen3.6-35B-A3B**: a route, the train, a pharmacy near the user. Mended after the first run: a translated layout keeps the English lines after its tags (the model had added blank lines between the legs of a journey: `src/chat/layout.c`, with a test); an arrival reads "06:26 get off at MARSALA" ("at" before both a time and a place came out wrong in Italian); "near me" is never a place only talked of. Overpass: a second instance (Private.coffee) when the first is busy, 25 s for each (`janas_https_get_ms`; the other sources keep 15 s), and both failures in the error.
+
## [2026-10-02] - Layouts: the services' data in the user's language, a brief to the model
- **The longest answers of the services come as data with a layout**: the aircraft over a sea and near a place, the weather now, the forecast and the sea. `janas-chat` fills the layout in the user's language and shows it, and the model reads only a brief of the figures. With Qwen3.6-35B-A3B, "how many aircraft over the Tyrrhenian now?" read 101 tokens and wrote 16, 3 s, against 3,011 and 334, 64 s; the weather in Trapani 162 tokens instead of about 400.
diff --git a/README.md b/README.md
index ad486e6..771ce90 100644
--- a/README.md
+++ b/README.md
@@ -54,6 +54,7 @@ Everything the engine does is chosen from what it measures, so another machine w
- **`janas-mcp`:** the other way round, the model offered as tools to MCP clients - a question to it, the embedding of a text ([below](#janas-as-an-mcp-server)).
- **`janas-flights`:** where a flight is and what flies over a sea or a place, as MCP tools, from the ADS-B receivers of the community, and today's schedules with a free AviationStack key: the first of Janas's services ([docs/services](docs/services/README.md)).
- **`janas-weather`:** the weather now, with what the nearest station measured, the forecast, the sea and its waves, and the warnings in force (in Italy the Civil Protection's levels), from free sources with no key ([docs/services/weather.md](docs/services/weather.md)).
+- **`janas-maps`:** roads and places: a route by car, bike or on foot, step by step in your language, journeys by public transport, what is near (fuel, a pharmacy, a cash machine...), where an address is; OpenStreetMap's data through free services with no key ([docs/services/maps.md](docs/services/maps.md)).
- **`janas-wiki`:** Wikipedia when you ask for it: its search, a page shown to you as it is (the introduction, then the section asked for) while the model reads only a note of it, and the pages about what lies around a place ([docs/services/wiki.md](docs/services/wiki.md)).
- **`janas-server`:** the model behind an HTTP API that follows OpenAI's, so that clients written for it can use a model running on this machine: chat and completions with tools, JSON output held to a schema and log-probabilities, the Responses API with its conversations, embeddings and moderations, a chat page of its own to try it from a browser ([below](#using-it-over-http)), and code completion for VSCodium and VS Code ([docs/code-completion.md](docs/code-completion.md)).
- **`janas-bench`:** measures the machine, fills its profile and writes a report.
@@ -294,7 +295,7 @@ printf 'Explain mixture of experts in one paragraph.\n/quit\n' \
### Janas's services
-The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
+The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-maps`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
**The services' tools are given when they are needed.** Written into the system message, the tools of three services made it four thousand tokens, over a minute of a large model before the first message, and every service more made it longer. The system message now holds a catalog, a line a service, and the model opens a service when a question needs it: that service's instructions and tools come back as the answer of the call, its tools can be called from then on, and the next reply is held to be a call (a small model told to call one made the answer up instead). With Qwen3.6-35B-A3B the system message went from 4,057 tokens to 616, and opening the weather costs about a thousand tokens, once in a conversation, when the first question about the weather comes. `--all-tools` writes them all into the system message as before.
@@ -595,6 +596,7 @@ It stands on the work of others, and says so:
- **GNU libmicrohttpd, yyjson and Mbed TLS** are compiled into the programs named below.
- **`janas-flights`** reads the positions of aircraft from [adsb.lol](https://adsb.lol) (data under the Open Database License) and [adsb.fi](https://adsb.fi), routes from [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's, schedules from [AviationStack](https://aviationstack.com); its tables of places are built from [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0) and [Natural Earth](https://www.naturalearthdata.com) (public domain).
- **`janas-weather`** reads forecasts and the sea from [Open-Meteo](https://open-meteo.com) (CC BY 4.0) and [MET Norway](https://api.met.no) (CC BY 4.0), the stations' reports from [aviationweather.gov](https://aviationweather.gov) (NOAA), warnings from [MeteoAlarm](https://meteoalarm.org) (EUMETNET) and the Italian alert levels from the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica) (CC BY 4.0). With no place named, the services ask [GeoJS](https://www.geojs.io) or [ipwho.is](https://ipwho.is) where the internet connection is.
+- **`janas-maps`** reads [OpenStreetMap](https://www.openstreetmap.org)'s data (© OpenStreetMap contributors, ODbL) through [Nominatim](https://nominatim.org), [Photon](https://photon.komoot.io), [Valhalla](https://github.com/valhalla/valhalla) and [OSRM](https://project-osrm.org) on the servers of [FOSSGIS](https://fossgis.de), and the [Overpass API](https://overpass-api.de) (with [Private.coffee's instance](https://overpass.private.coffee) when it is busy), and journeys by public transport from [Transitous](https://transitous.org), over the operators' open timetables.
- **`janas-wiki`** reads [Wikipedia](https://www.wikipedia.org) through its API; the text is Wikipedia's, under CC BY-SA 4.0, and every answer gives the page's address.
- **The people who tried it on their own machines** and reported what they saw, in the issues of this repository: their reports changed the engine more than once (the threads it picks, the prompt's progress, the GPU's diagnosis).
diff --git a/docs/services/README.md b/docs/services/README.md
index 9c6a4fb..5ac8035 100644
--- a/docs/services/README.md
+++ b/docs/services/README.md
@@ -1,10 +1,11 @@
# Janas's services
-A service of Janas is a program that brings data of the world - flights, the weather, an encyclopedia - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
+A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
| Service | What it answers | Key |
|---|---|---|
| [`janas-flights`](flights.md) | where a flight is and what it is doing, its times, the flights of a route, what flies over a sea or near a place | none for live data; a free one of your own for schedules |
+| [`janas-maps`](maps.md) | a route by car, bike or on foot, step by step; journeys by public transport; what is near a place; where an address is | none |
| [`janas-weather`](weather.md) | the weather now (a model's and a station's), the forecast, the sea and its waves, the warnings in force | none |
| [`janas-wiki`](wiki.md) | Wikipedia's search, its pages as text, the pages about what lies around a place | none |
@@ -15,7 +16,7 @@ What every service does the same way:
- **It says when to use it.** A service tells the client's model when its tools apply: a question on the subject is enough, the tools need not be named, and the model is told not to name them in its answers.
- **Keys stay put.** A key is read from the service's file under `~/.config/janas/` or from a variable of its environment, and never printed, not even in an error.
- **Only what was asked.** A service's tools are used for its subject when the user asks about it, and never because of another's answer: no weather or flights for the town a page names, unless the user asks for them.
-- **Data and a layout.** The longest answers - the aircraft over a sea or near a place, the weather now, the forecast, the sea - come as data with a layout (MCP's `structuredContent`, the layout in `_meta`) besides their English text. `janas-chat` fills the layout in the user's language and shows it, and gives the model only a brief: the figures it needs to answer in a line or two. A list of forty aircraft cost the model 3,000 tokens to read and as many to write again; it now reads about a hundred. The layout in another language than English is asked of the model once, on the side of the conversation: it gets the text with the layout's tags as numbered markers and its words numbered one a line, never the tags themselves, which are put back and checked (a word it leaves out stays English; a marker left out, and the English layout is used). The terms of the scales - the Beaufort forces, the Douglas sea states - are not asked: in Italian, French, Spanish and German they come from a glossary in `janas-chat`, with the names the national weather services give them, and the request gives the model the terms of the sea for the rest of the text. It is kept in `~/.config/janas/layouts`, one file a layout and language, where it can be corrected by hand; a new version of a layout is translated anew. The language is the computer's (`LANG`).
+- **Data and a layout.** The longest answers - the aircraft over a sea or near a place, the weather now, the forecast, the sea, the routes and journeys and places of the maps - come as data with a layout (MCP's `structuredContent`, the layout in `_meta`) besides their English text. `janas-chat` fills the layout in the user's language and shows it, and gives the model only a brief: the figures it needs to answer in a line or two. A list of forty aircraft cost the model 3,000 tokens to read and as many to write again; it now reads about a hundred. The layout in another language than English is asked of the model once, on the side of the conversation: it gets the text with the layout's tags as numbered markers and its words numbered one a line, never the tags themselves, which are put back and checked (a word it leaves out stays English; a marker left out, and the English layout is used). The terms of the scales - the Beaufort forces, the Douglas sea states - are not asked: in Italian, French, Spanish and German they come from a glossary in `janas-chat`, with the names the national weather services give them, and the request gives the model the terms of the sea for the rest of the text. It is kept in `~/.config/janas/layouts`, one file a layout and language, where it can be corrected by hand; a new version of a layout is translated anew. The language is the computer's (`LANG`).
- **What is the user's goes to the user.** A page of Wikipedia is shown as it is, and the model reads only a note of it: MCP marks each part of an answer with its audience, and `janas-chat` shows the parts meant for the user alone instead of giving them to the model. A client that does not heed the audience gives the model both.
- **Here, when no place is named.** A question about "here" takes where the user is: `JANAS_LOCATION` when set (a city, `lat,lon`, or `off`), else the internet connection's position (GeoJS, ipwho.is), else the city of the computer's time zone; the answer says which, so the model can say it is a guess ([details](weather.md#when-no-place-is-named)).
diff --git a/docs/services/maps.md b/docs/services/maps.md
new file mode 100644
index 0000000..1a8b950
--- /dev/null
+++ b/docs/services/maps.md
@@ -0,0 +1,61 @@
+# janas-maps
+
+Roads and places for `janas-chat` or any other MCP client (see [the services](README.md)): a route by car, bike or on foot, journeys by public transport, what is near a place, where a place or an address is. OpenStreetMap's data through free services: no key, no account.
+
+## The tools
+
+- **`maps_route`** - the route between two places, or through a third (`via`), by car (the default), bike or on foot (`mode`), avoiding tolls, motorways or ferries when asked (`avoid`): its length, its time without traffic, the roads it mostly takes, whether it has tolls or a ferry, up to two other ways, the way step by step, and a link to the route on openstreetmap.org. The steps are written by the router in the computer's language (Italian with `LANG=it_IT.UTF-8`; English for a language it does not know). When Valhalla does not answer, OSRM gives the route without its steps.
+- **`maps_transit`** - journeys by public transport between two places, leaving now or at a time (`when`: `HH:MM` or `YYYY-MM-DD HH:MM`, the start's local time; a time of the day already gone is tomorrow's), or arriving by it (`arrive_by`): up to five, each with its times, length and changes, and leg by leg the line, its operator, the stops and the walks between them.
+- **`maps_nearby`** - the places of a kind within a radius of a place (2 km unless asked, up to 10), nearest first, at most ten, with how far and which way, their address, opening hours and phone when mapped. The kinds are a list, so that the model picks one and never writes a query: fuel, charging, parking, pharmacy, hospital, doctor, atm, bank, post_office, police, supermarket, restaurant, cafe, bar, hotel, toilets, train_station, bus_stop, museum, attraction.
+- **`maps_find`** - where a place or an address is: its full address, its coordinates, what it is on the map, and a link to it; for a point, what is there.
+
+A place is a name or an address, best with its town ("Via Roma 10, Trapani", "Stazione Centrale, Palermo", "Colosseo"), or `lat,lon`. The second place of a route is looked for near the first, so that "Stazione Centrale" on the way from Trapani is Palermo's. With no start named, the start is where the user is, as for the weather ([details](weather.md#when-no-place-is-named)), and the answer says so.
+
+## The answers
+
+Every answer is data with a layout (see [the services](README.md)): `janas-chat` shows the user the whole of it in the user's language - the steps, the journeys leg by leg, the list of places - and gives the model only a brief of the figures, from which it answers in a line or two. A route of a hundred steps costs the model the same as one of ten.
+
+## Where the data comes from
+
+| Data | Source | Key |
+|---|---|---|
+| places and addresses | [Nominatim](https://nominatim.org) (OpenStreetMap Foundation), [Photon](https://photon.komoot.io) (komoot) when Nominatim does not answer | none |
+| routes | [Valhalla](https://github.com/valhalla/valhalla) and [OSRM](https://project-osrm.org) on the servers of [FOSSGIS](https://fossgis.de/arbeitsgruppen/osm-server/nutzungsbedingungen/) | none |
+| public transport | [Transitous](https://transitous.org), from the operators' open timetables | none |
+| what is near | [Overpass API](https://overpass-api.de), [Private.coffee's instance](https://overpass.private.coffee) when the first is busy | none |
+| where the user is | [GeoJS](https://www.geojs.io), [ipwho.is](https://ipwho.is) | none |
+
+- **The data is OpenStreetMap's**, © OpenStreetMap contributors, under the [Open Database License](https://www.openstreetmap.org/copyright): every answer says so.
+- **The services are run by volunteers for moderate use**, and each asks for the same: a User-Agent naming the program and where it lives (`janas-maps/<version> (+https://github.com/prabanta-dev/janas)`) and at most one request a second; `janas-maps` waits as long as it must between two requests to a server, and keeps the answers a while (places a week, routes ten minutes, journeys two minutes, places around an hour). Transitous asks to be used by open-source, non-commercial projects, as Janas is.
+- **Each server can be changed**, as FOSSGIS asks of programs, with `JANAS_NOMINATIM_URL`, `JANAS_PHOTON_URL`, `JANAS_VALHALLA_URL`, `JANAS_OSRM_URL`, `JANAS_TRANSITOUS_URL`, `JANAS_OVERPASS_URL` and `JANAS_OVERPASS_URL2`: an instance of your own, for instance.
+- **Times by road are without traffic**: no free source has it.
+- **Long routes**: FOSSGIS' Valhalla routes up to 1,500 km, and its OSRM knows Europe only; longer routes, or routes off Europe's roads when Valhalla does not answer, are said to be unavailable rather than made up.
+- **Public transport is as good as the open timetables**: Transitous has those the operators publish, the trains of Trenitalia among them, not every bus company's. Live times are marked when there are any; check the operator before you go.
+- **What is near is what is mapped**: a pharmacy may be named after its pharmacist, and opening hours are in OpenStreetMap's notation, sometimes old. Distances are as the crow flies. Overpass is at times too busy to answer: the second instance is asked, and when neither answers the answer says to try again in a minute.
+
+## Running it
+
+```sh
+janas-maps
+```
+
+It speaks MCP over its standard input and output and writes what it does on its standard error. In other clients:
+
+```sh
+claude mcp add maps -- /path/to/janas-maps
+```
+
+```json
+{"mcpServers": {"maps": {"command": "/path/to/janas-maps"}}}
+```
+
+## What has been run
+
+2 October 2026, over the protocol, in the release and AddressSanitizer builds, with `LANG=it_IT.UTF-8`:
+
+- Trapani to Palermo by car: 110 km, 1 h 37 min, by the A29, with two other ways and the steps in Italian; through Alcamo, avoiding tolls; to Erice on foot; to Marsala by bike; from "here" (Palermo, by GeoJS) to Erice. Trapani to New York: no route, with the reasons (Valhalla's limit, OSRM's map).
+- Trapani to Palermo's central station by public transport at 9:00: five journeys, the first a regional train to Marsala and a coach to Palermo; Milan's central station to Rome Termini arriving by 8:00 on 5 October.
+- Pharmacies within 1 km of Piazza Vittorio Emanuele in Trapani, cash machines within 500 m of the Colosseum, fuel near "here".
+- The Colosseum, a point beside it, and a place that does not exist.
+
+In `janas-chat` with Qwen3.6-35B-A3B, the same day, in Italian: "Come arrivo a Palermo da Trapani?" (the route by car, the layout written in Italian once), "E in treno?" (five journeys, leg by leg), "C'è una farmacia vicino a me?" (where the user is, by GeoJS: 22 pharmacies within 2 km). The first run showed three faults, mended and run again: blank lines the model had added between the legs, "14:53 alle PIRAINETO" for an arrival (the English said "at" for both a time and a place), and a place taken from the conversation for "near me". The second instance of Overpass was asked when the first was made to fail; on 2 October it did not answer in time.
diff --git a/src/chat/layout.c b/src/chat/layout.c
index b630803..9cfb67b 100644
--- a/src/chat/layout.c
+++ b/src/chat/layout.c
@@ -157,6 +157,8 @@ static const char SYSTEM[] =
struct coded {
struct janas_buf text; /* for the model */
char **tags; /* {N}: tags[N - 1] */
+ char **gaps; /* gaps[N - 1]: the spaces and lines after {N} */
+ char *to_tag; /* to_tag[N - 1]: {N + 1} comes right after */
size_t n_tags;
char **keys; /* word N: keys[N - 1], and its English text */
char **english;
@@ -166,14 +168,18 @@ struct coded {
static void coded_free(struct coded *c)
{
janas_buf_free(&c->text);
- for (size_t i = 0; i < c->n_tags; i++)
+ for (size_t i = 0; i < c->n_tags; i++) {
free(c->tags[i]);
+ free(c->gaps ? c->gaps[i] : NULL);
+ }
+ free(c->to_tag);
for (size_t i = 0; i < c->n_keys; i++)
free(c->keys[i]);
for (size_t i = 0; i < c->n_english; i++)
free(c->english[i]);
free(c->english);
free(c->tags);
+ free(c->gaps);
free(c->keys);
}
@@ -235,8 +241,23 @@ static int encode(const char *en, struct coded *c)
if (!close)
return -1;
size_t end = (size_t)(close - en) + 2;
+ size_t nt = c->n_tags;
+ char **g = realloc(c->gaps, (nt + 1) * sizeof *g);
+ char *t = g ? realloc(c->to_tag, nt + 1) : NULL;
+ if (g)
+ c->gaps = g;
+ if (!t)
+ return -1;
+ c->to_tag = t;
+ g[nt] = NULL;
if (push(&c->tags, &c->n_tags, open, end - upto) != 0)
return -1;
+ size_t sp = end;
+ while (sp < ln && (en[sp] == ' ' || en[sp] == '\n'))
+ sp++;
+ t[nt] = sp + 1 < ln && en[sp] == '{' && en[sp + 1] == '{';
+ if (!(g[nt] = strndup(en + end, sp - end)))
+ return -1;
janas_buf_printf(&c->text, "{%zu}", c->n_tags);
i = end;
}
@@ -296,6 +317,22 @@ static char *decode(const struct coded *c, const char *ans, char *why,
}
janas_buf_puts(&out, c->tags[k - 1]);
i = (size_t)(end - ans) + 1;
+ /* the lines after a tag are the English ones: the 35B
+ added blank lines between the legs of a journey. So are
+ the spaces between two tags with nothing else between
+ them; those within a sentence are the language's. */
+ size_t j = i;
+ int nl = 0;
+ while (j < tn &&
+ (ans[j] == ' ' || ans[j] == '\n' || ans[j] == '\r'))
+ nl |= ans[j++] != ' ';
+ const char *g = c->gaps[k - 1];
+ if ((c->to_tag[k - 1] && j < tn && ans[j] == '{' &&
+ strtoul(ans + j + 1, &end, 10) == k + 1 && *end == '}') ||
+ (nl && strchr(g, '\n'))) {
+ janas_buf_puts(&out, g);
+ i = j;
+ }
continue;
}
}
diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.c
index a009fa1..de19fbf 100644
--- a/src/chat/mcp_chat.c
+++ b/src/chat/mcp_chat.c
@@ -38,6 +38,9 @@ static const struct {
{"flights", "flights and aircraft: where a flight is and what it is "
"doing, today's flights of a route, what flies over a sea "
"or near a place"},
+ {"maps", "roads and places: a route by car, bike or on foot, public "
+ "transport between places, what is near (fuel, a pharmacy...), "
+ "where an address is"},
{"weather", "the weather now and the forecast, the sea and its waves, "
"weather warnings"},
{"wiki", "Wikipedia, when the user asks for it: a page shown to the "
diff --git a/src/common/https_get.c b/src/common/https_get.c
index 4caf84a..8cf66c9 100644
--- a/src/common/https_get.c
+++ b/src/common/https_get.c
@@ -18,6 +18,14 @@
int janas_https_get(const char *url, const char *const *headers,
size_t n_headers, struct janas_buf *out, char *err,
size_t err_len)
+{
+ return janas_https_get_ms(url, headers, n_headers, TIMEOUT_MS, out, err,
+ err_len);
+}
+
+int janas_https_get_ms(const char *url, const char *const *headers,
+ size_t n_headers, int timeout_ms, struct janas_buf *out,
+ char *err, size_t err_len)
{
char where[4096];
snprintf(where, sizeof where, "%s", url);
@@ -27,7 +35,7 @@ int janas_https_get(const char *url, const char *const *headers,
return -1;
struct janas_http h;
if (janas_http_request(&h, &u, "GET", headers, n_headers, NULL, 0,
- TIMEOUT_MS, NULL, err, err_len) != 0)
+ timeout_ms, NULL, err, err_len) != 0)
return -1;
int status = h.head.status;
if (status >= 300 && status < 400 && h.head.location[0]) {
@@ -37,7 +45,7 @@ int janas_https_get(const char *url, const char *const *headers,
}
out->n = 0;
int r;
- while ((r = janas_http_body(&h, out, TIMEOUT_MS)) == 1)
+ while ((r = janas_http_body(&h, out, timeout_ms)) == 1)
if (out->n > MAX_BODY) {
r = -1;
break;
diff --git a/src/common/https_get.h b/src/common/https_get.h
index 033e06d..898960d 100644
--- a/src/common/https_get.h
+++ b/src/common/https_get.h
@@ -16,5 +16,10 @@
int janas_https_get(const char *url, const char *const *headers,
size_t n_headers, struct janas_buf *out, char *err,
size_t err_len);
+/* The same, waiting at most timeout_ms for each part of the answer
+ (janas_https_get: 15 s). */
+int janas_https_get_ms(const char *url, const char *const *headers,
+ size_t n_headers, int timeout_ms, struct janas_buf *out,
+ char *err, size_t err_len);
#endif
diff --git a/src/maps/data.c b/src/maps/data.c
new file mode 100644
index 0000000..e08fdc2
--- /dev/null
+++ b/src/maps/data.c
@@ -0,0 +1,277 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * data.c - what janas-maps read, as the data of its layouts (see maps.h,
+ * layouts.c and common/template.h): JSON objects whose fields the layouts
+ * name. Distances and times are numbers, the words around them the
+ * layout's, so that a client shows them in the user's language.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/geo.h"
+#include "maps.h"
+
+/* A field is written even when empty: a layout looks a name up in the
+ item, then in what holds it (common/template.h), and a step without its
+ own distance would show the whole route's. */
+void mp_jstr(struct janas_buf *b, const char *key, const char *v)
+{
+ if (!v)
+ v = "";
+ janas_buf_printf(b, ", \"%s\": ", key);
+ janas_json_write_str(b, v, strlen(v));
+}
+
+void mp_jnum(struct janas_buf *b, const char *key, double v, int decimals)
+{
+ if (!isnan(v))
+ janas_buf_printf(b, ", \"%s\": %.*f", key, decimals, v);
+}
+
+void mp_jplace(struct janas_buf *b, const char *key, const struct mp_place *p)
+{
+ janas_buf_printf(b, ", \"%s\": {\"name\": ", key);
+ janas_json_write_str(b, p->name, strlen(p->name));
+ if (strcmp(p->address, p->name) != 0)
+ mp_jstr(b, "address", p->address);
+ mp_jstr(b, "city", p->city);
+ mp_jnum(b, "lat", p->lat, 5);
+ mp_jnum(b, "lon", p->lon, 5);
+ mp_jstr(b, "how", p->how);
+ janas_buf_puts(b, "}");
+}
+
+void mp_jtime(struct janas_buf *b, double min)
+{
+ long m = lround(min);
+ if (m < 1)
+ m = 1;
+ janas_buf_printf(b, ", \"h\": %ld, \"min\": %ld", m / 60, m % 60);
+}
+
+/* a distance: "km" from a kilometre, "m" below it, to ten metres; the
+ other one 0 */
+static void jdist(struct janas_buf *b, double km)
+{
+ if (isnan(km) || km <= 0)
+ janas_buf_puts(b, ", \"km\": 0, \"m\": 0");
+ else if (km >= 10)
+ janas_buf_printf(b, ", \"km\": %.0f, \"m\": 0", km);
+ else if (km >= 1)
+ janas_buf_printf(b, ", \"km\": %.1f, \"m\": 0", km);
+ else
+ janas_buf_printf(b, ", \"km\": 0, \"m\": %.0f",
+ fmax(10, round(km * 100) * 10));
+}
+
+void mp_jclock(struct janas_buf *b, const char *key, time_t t, const char *tz)
+{
+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;
+ if (tz && *tz)
+ setenv("TZ", tz, 1);
+ tzset();
+ struct tm lt, nt;
+ time_t now = time(NULL);
+ localtime_r(&t, &lt);
+ localtime_r(&now, &nt);
+ janas_buf_printf(b, ", \"%s\": {\"at\": \"%02d:%02d\"", key, lt.tm_hour,
+ lt.tm_min);
+ if (lt.tm_yday != nt.tm_yday || lt.tm_year != nt.tm_year)
+ janas_buf_printf(b,
+ ", \"date\": true, \"wd\": %d, \"day\": %d, "
+ "\"mon\": %d",
+ lt.tm_wday, lt.tm_mday, lt.tm_mon + 1);
+ janas_buf_puts(b, "}");
+ if (tz && *tz) {
+ if (old)
+ setenv("TZ", old, 1);
+ else
+ unsetenv("TZ");
+ tzset();
+ }
+ free(old);
+}
+
+/* An object whose members are written as ", key: value": open it, and
+ close it with the first comma taken away. */
+static size_t open_obj(struct janas_buf *b)
+{
+ janas_buf_puts(b, "{");
+ return b->n;
+}
+
+static void close_obj(struct janas_buf *b, size_t at)
+{
+ if (!b->oom && b->n >= at + 2 && memcmp(b->p + at, ", ", 2) == 0) {
+ memmove(b->p + at, b->p + at + 2, b->n - at - 2);
+ b->n -= 2;
+ }
+ janas_buf_puts(b, "}");
+}
+
+/* ---- maps_route ---- */
+
+static void jroute(struct janas_buf *b, const struct mp_route *r)
+{
+ jdist(b, r->km);
+ mp_jtime(b, r->min);
+ janas_buf_printf(b, ", \"toll\": %s, \"ferry\": %s",
+ r->toll ? "true" : "false", r->ferry ? "true" : "false");
+ mp_jstr(b, "roads", r->roads);
+}
+
+void mp_route_data(struct janas_buf *d, const struct mp_place *from,
+ const struct mp_place *via, const struct mp_place *to,
+ const char *mode, const struct mp_routes *rs)
+{
+ const struct mp_route *r = &rs->r[0];
+ janas_buf_printf(d, "{\"mode\": \"%s\", \"source\": \"%s\"", mode,
+ rs->source);
+ mp_jplace(d, "from", from);
+ if (via)
+ mp_jplace(d, "via", via);
+ mp_jplace(d, "to", to);
+ jroute(d, r);
+ if (rs->n > 1) {
+ janas_buf_puts(d, ", \"alternatives\": [");
+ for (int i = 1; i < rs->n; i++) {
+ if (i > 1)
+ janas_buf_puts(d, ", ");
+ size_t o = open_obj(d);
+ jroute(d, &rs->r[i]);
+ close_obj(d, o);
+ }
+ janas_buf_puts(d, "]");
+ }
+ janas_buf_printf(d, ", \"n_steps\": %d", r->n_step);
+ if (r->n_step) {
+ janas_buf_puts(d, ", \"steps\": [");
+ for (int i = 0; i < r->n_step; i++) {
+ janas_buf_puts(d, i ? ", {\"text\": " : "{\"text\": ");
+ janas_json_write_str(d, r->step[i].text, strlen(r->step[i].text));
+ jdist(d, r->step[i].km);
+ janas_buf_puts(d, "}");
+ }
+ janas_buf_puts(d, "]");
+ }
+ janas_buf_printf(d, ", \"cut\": %d", r->cut);
+ /* the route on OpenStreetMap's site, drawn by the same engine */
+ static const char *const engine[][2] = {
+ {"car", "fossgis_valhalla_car"},
+ {"bike", "fossgis_valhalla_bicycle"},
+ {"foot", "fossgis_valhalla_foot"}};
+ for (size_t i = 0; !via && i < sizeof engine / sizeof *engine; i++)
+ if (strcmp(mode, engine[i][0]) == 0)
+ janas_buf_printf(d,
+ ", \"link\": \"https://www.openstreetmap.org/"
+ "directions?engine=%s&route=%.5f%%2C%.5f%%3B%.5f"
+ "%%2C%.5f\"",
+ engine[i][1], from->lat, from->lon, to->lat,
+ to->lon);
+ janas_buf_puts(d, "}");
+}
+
+/* ---- maps_transit ---- */
+
+/* START and END are the journey's ends, as Transitous names them */
+static const char *stop_name(const char *s, const struct mp_place *from,
+ const struct mp_place *to)
+{
+ if (strcmp(s, "START") == 0)
+ return from->name;
+ if (strcmp(s, "END") == 0)
+ return to->name;
+ return s;
+}
+
+void mp_transit_data(struct janas_buf *d, const struct mp_place *from,
+ const struct mp_place *to, const struct mp_transit *tr)
+{
+ janas_buf_puts(d, "{\"source\": \"Transitous\"");
+ mp_jplace(d, "from", from);
+ mp_jplace(d, "to", to);
+ janas_buf_printf(d, ", \"count\": %d, \"trips\": [", tr->n);
+ for (int i = 0; i < tr->n; i++) {
+ const struct mp_trip *t = &tr->t[i];
+ janas_buf_printf(d, "%s{\"transfers\": %d", i ? ", " : "",
+ t->transfers);
+ mp_jclock(d, "dep", t->dep, tr->tz);
+ mp_jclock(d, "arr", t->arr, tr->tz);
+ mp_jtime(d, difftime(t->arr, t->dep) / 60);
+ janas_buf_puts(d, ", \"legs\": [");
+ for (int k = 0; k < t->n_leg; k++) {
+ const struct mp_leg *g = &t->leg[k];
+ janas_buf_puts(d, k ? ", {" : "{");
+ int walk = strcmp(g->mode, "WALK") == 0;
+ janas_buf_printf(d, "\"walk\": %s, \"mode\": \"%s\"",
+ walk ? "true" : "false", g->mode);
+ mp_jtime(d, difftime(g->arr, g->dep) / 60);
+ jdist(d, walk ? g->walk_m / 1000 : NAN);
+ mp_jstr(d, "line", g->line);
+ mp_jstr(d, "agency", g->agency);
+ mp_jstr(d, "headsign", g->headsign);
+ janas_buf_printf(d, ", \"live\": %s",
+ g->real_time ? "true" : "false");
+ mp_jstr(d, "from", stop_name(g->from, from, to));
+ mp_jclock(d, "dep", g->dep, tr->tz);
+ mp_jstr(d, "to", stop_name(g->to, from, to));
+ mp_jclock(d, "arr", g->arr, tr->tz);
+ janas_buf_puts(d, "}");
+ }
+ janas_buf_puts(d, "]");
+ janas_buf_printf(d, ", \"cut\": %d", t->cut);
+ janas_buf_puts(d, "}");
+ }
+ janas_buf_puts(d, "]");
+ mp_jstr(d, "tz", tr->tz);
+ janas_buf_puts(d, "}");
+}
+
+/* ---- maps_nearby ---- */
+
+void mp_near_data(struct janas_buf *d, const struct mp_place *at,
+ const char *what, double radius_km, const struct mp_near *nr)
+{
+ janas_buf_printf(d, "{\"what\": \"%s\"", what);
+ mp_jplace(d, "place", at);
+ janas_buf_printf(d, ", \"radius\": %g, \"found\": %d, \"count\": %d",
+ radius_km, nr->found, nr->n);
+ janas_buf_puts(d, ", \"items\": [");
+ for (int i = 0; i < nr->n; i++) {
+ const struct mp_poi *p = &nr->p[i];
+ if (i)
+ janas_buf_puts(d, ", ");
+ size_t o = open_obj(d);
+ mp_jstr(d, "name", p->name);
+ jdist(d, p->m / 1000);
+ mp_jstr(d, "dir",
+ p->m >= 10
+ ? geo_compass(geo_bearing(at->lat, at->lon, p->lat, p->lon))
+ : "");
+ mp_jstr(d, "address", p->address);
+ mp_jstr(d, "hours", p->hours);
+ mp_jstr(d, "phone", p->phone);
+ mp_jstr(d, "osm", p->osm);
+ close_obj(d, o);
+ }
+ janas_buf_puts(d, "]}");
+}
+
+/* ---- maps_find ---- */
+
+void mp_find_data(struct janas_buf *d, const struct mp_place *p)
+{
+ size_t o = open_obj(d);
+ mp_jplace(d, "place", p);
+ mp_jstr(d, "kind", p->kind);
+ mp_jstr(d, "osm", p->osm);
+ janas_buf_printf(d,
+ ", \"link\": \"https://www.openstreetmap.org/?mlat=%.5f&"
+ "mlon=%.5f#map=17/%.5f/%.5f\"",
+ p->lat, p->lon, p->lat, p->lon);
+ close_obj(d, o);
+}
diff --git a/src/maps/fetch.c b/src/maps/fetch.c
new file mode 100644
index 0000000..44a2831
--- /dev/null
+++ b/src/maps/fetch.c
@@ -0,0 +1,171 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * fetch.c - janas-maps asks its sources (see maps.h): a GET over HTTPS
+ * with the User-Agent they ask for, at most one request a second to each
+ * host (Nominatim's and FOSSGIS' rule), the answers kept a while: a
+ * conversation asks the same route again, by bike after by car, and the
+ * places are found once.
+ */
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/https_get.h"
+#include "maps.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+#define N_KEPT 48
+#define N_HOSTS 8
+
+static struct {
+ char *url;
+ time_t at;
+ int keep_s;
+ struct janas_buf body;
+} kept[N_KEPT];
+
+static struct {
+ char host[96];
+ struct timespec last;
+} hosts[N_HOSTS];
+
+static double since(const struct timespec *t)
+{
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return (double)(now.tv_sec - t->tv_sec) +
+ (double)(now.tv_nsec - t->tv_nsec) * 1e-9;
+}
+
+/* Waits until the host of url was last asked over a second ago. */
+static void pace(const char *url)
+{
+ const char *h = strstr(url, "://");
+ h = h ? h + 3 : url;
+ size_t n = strcspn(h, "/?:");
+ int slot = -1;
+ for (int i = 0; i < N_HOSTS; i++) {
+ if (strlen(hosts[i].host) == n && strncmp(hosts[i].host, h, n) == 0) {
+ slot = i;
+ break;
+ }
+ if (slot < 0 && !hosts[i].host[0])
+ slot = i;
+ }
+ if (slot < 0)
+ slot = 0;
+ if (strlen(hosts[slot].host) == n && strncmp(hosts[slot].host, h, n) == 0) {
+ double wait = 1.1 - since(&hosts[slot].last);
+ if (wait > 0 && wait <= 1.1) {
+ struct timespec ts = {.tv_sec = (time_t)wait};
+ ts.tv_nsec = (long)((wait - (double)ts.tv_sec) * 1e9);
+ nanosleep(&ts, NULL);
+ }
+ } else {
+ snprintf(hosts[slot].host, sizeof hosts[slot].host, "%.*s", (int)n, h);
+ }
+ clock_gettime(CLOCK_MONOTONIC, &hosts[slot].last);
+}
+
+int mp_fetch(const char *url, int keep_s, struct janas_buf *out, char *err,
+ size_t err_len)
+{
+ return mp_fetch_ms(url, keep_s, 15000, out, err, err_len);
+}
+
+int mp_fetch_ms(const char *url, int keep_s, int timeout_ms,
+ struct janas_buf *out, char *err, size_t err_len)
+{
+ time_t now = time(NULL);
+ int slot = 0;
+ for (int i = 0; i < N_KEPT; i++) {
+ if (kept[i].url && strcmp(kept[i].url, url) == 0 &&
+ now - kept[i].at < kept[i].keep_s) {
+ out->n = 0;
+ janas_buf_put(out, kept[i].body.p, kept[i].body.n);
+ janas_buf_put(out, "", 1);
+ out->n--;
+ return out->oom ? -1 : 200;
+ }
+ if (kept[i].at < kept[slot].at)
+ slot = i;
+ }
+ /* the sources' rules: a User-Agent naming the program and a way to
+ reach its authors (Transitous: its version too); the stock ones of
+ libraries are refused */
+ static const char *const agent[] = {
+ "User-Agent: janas-maps/" JANAS_VERSION
+ " (+https://github.com/prabanta-dev/janas)"};
+ pace(url);
+ int status =
+ janas_https_get_ms(url, agent, 1, timeout_ms, out, err, err_len);
+ if (status == 200 && keep_s > 0 && !out->oom) {
+ free(kept[slot].url);
+ janas_buf_free(&kept[slot].body);
+ kept[slot].url = strdup(url);
+ kept[slot].at = now;
+ kept[slot].keep_s = keep_s;
+ kept[slot].body = (struct janas_buf){0};
+ janas_buf_put(&kept[slot].body, out->p, out->n);
+ if (!kept[slot].url || kept[slot].body.oom) {
+ free(kept[slot].url);
+ janas_buf_free(&kept[slot].body);
+ kept[slot].url = NULL;
+ kept[slot].at = 0;
+ }
+ }
+ return status;
+}
+
+void mp_fetch_free(void)
+{
+ for (int i = 0; i < N_KEPT; i++) {
+ free(kept[i].url);
+ janas_buf_free(&kept[i].body);
+ }
+ memset(kept, 0, sizeof kept);
+}
+
+const char *mp_base(const char *env, const char *def)
+{
+ const char *v = getenv(env);
+ return v && *v ? v : def;
+}
+
+void mp_url_put(struct janas_buf *b, const char *s)
+{
+ static const char hex[] = "0123456789ABCDEF";
+ for (; *s; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
+ janas_buf_put(b, (const char *)&c, 1);
+ else
+ janas_buf_printf(b, "%%%c%c", hex[c >> 4], hex[c & 15]);
+ }
+}
+
+const char *mp_lang(void)
+{
+ static char lang[8];
+ static const char *const vars[] = {"LC_ALL", "LC_MESSAGES", "LANG"};
+ for (size_t i = 0; i < sizeof vars / sizeof *vars; i++) {
+ const char *v = getenv(vars[i]);
+ if (!v || !*v)
+ continue;
+ size_t n = strcspn(v, "_.@");
+ int ok = n == 2 && islower((unsigned char)v[0]) &&
+ islower((unsigned char)v[1]);
+ if (ok) {
+ snprintf(lang, sizeof lang, "%.2s", v);
+ return lang;
+ }
+ break; /* the first one set rules, "C" too */
+ }
+ return "en";
+}
diff --git a/src/maps/layouts.c b/src/maps/layouts.c
new file mode 100644
index 0000000..f7c9e84
--- /dev/null
+++ b/src/maps/layouts.c
@@ -0,0 +1,251 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * layouts.c - the layouts of janas-maps' answers (see maps.h and
+ * common/template.h): the text the user reads, filled with the data in
+ * English here and in the user's language by a client that translates the
+ * layout once (janas-chat), and the brief, all the model reads of it. A
+ * route's steps come from Valhalla already in the computer's language.
+ */
+#include "maps.h"
+
+/* The compass, abbreviated. */
+#define DIR_WORDS \
+ "dir.N = N\n" \
+ "dir.NNE = NNE\n" \
+ "dir.NE = NE\n" \
+ "dir.ENE = ENE\n" \
+ "dir.E = E\n" \
+ "dir.ESE = ESE\n" \
+ "dir.SE = SE\n" \
+ "dir.SSE = SSE\n" \
+ "dir.S = S\n" \
+ "dir.SSW = SSW\n" \
+ "dir.SW = SW\n" \
+ "dir.WSW = WSW\n" \
+ "dir.W = W\n" \
+ "dir.WNW = WNW\n" \
+ "dir.NW = NW\n" \
+ "dir.NNW = NNW\n"
+
+/* The days of the week (0 Sunday) and the months. */
+#define DATE_WORDS \
+ "wd.0 = Sunday\n" \
+ "wd.1 = Monday\n" \
+ "wd.2 = Tuesday\n" \
+ "wd.3 = Wednesday\n" \
+ "wd.4 = Thursday\n" \
+ "wd.5 = Friday\n" \
+ "wd.6 = Saturday\n" \
+ "mon.1 = January\n" \
+ "mon.2 = February\n" \
+ "mon.3 = March\n" \
+ "mon.4 = April\n" \
+ "mon.5 = May\n" \
+ "mon.6 = June\n" \
+ "mon.7 = July\n" \
+ "mon.8 = August\n" \
+ "mon.9 = September\n" \
+ "mon.10 = October\n" \
+ "mon.11 = November\n" \
+ "mon.12 = December\n"
+
+/* Where the user is, as the locator says how it knows it. */
+#define HOW_WORDS \
+ "how.as set on the computer (JANAS_LOCATION) = as set on the computer " \
+ "(JANAS_LOCATION)\n" \
+ "how.estimated from the internet connection (GeoJS) = estimated from " \
+ "the internet connection (GeoJS)\n" \
+ "how.estimated from the internet connection (ipwho.is) = estimated from " \
+ "the internet connection (ipwho.is)\n" \
+ "how.a rough guess, the city of the computer's time zone = a rough " \
+ "guess, the city of the computer's time zone\n"
+
+/* A place, with where the user is when it was not named. */
+#define PLACE(p) \
+ "{{" p ".name}}{{#" p ".how}} (where the user is, {{" p ".how|how}})" \
+ "{{/" p ".how}}"
+
+/* A time, with its day when it is not today. */
+#define CLOCK(t) \
+ "{{" t ".at}}{{#" t ".date}} {{" t ".wd|wd}} {{" t ".day}} {{" t \
+ ".mon|mon}}{{/" t ".date}}"
+
+#define FROM PLACE("from")
+#define AT PLACE("place")
+#define DEP CLOCK("dep")
+#define ARR CLOCK("arr")
+
+#define DIST "{{#km}}{{km}} km{{/km}}{{#m}}{{m}} m{{/m}}"
+#define TIME "{{#h}}{{h}} h {{/h}}{{min}} min"
+
+#define OSM "data © OpenStreetMap contributors (ODbL)"
+
+const char MP_ROUTE_LAYOUT[] =
+ "From " FROM "{{#via}} through {{via.name}}{{/via}} to "
+ "{{to.name}} {{mode|mode}}: " DIST ", about " TIME " without traffic"
+ "{{#roads}}, by {{roads}}{{/roads}}{{#toll}}; with tolls{{/toll}}"
+ "{{#ferry}}; with a ferry{{/ferry}}.\n"
+ "{{#from.address}}\n"
+ "- from: {{from.address}}\n"
+ "{{/from.address}}\n"
+ "{{#via.address}}\n"
+ "- through: {{via.address}}\n"
+ "{{/via.address}}\n"
+ "{{#to.address}}\n"
+ "- to: {{to.address}}\n"
+ "{{/to.address}}\n"
+ "{{#alternatives}}\n"
+ "Another way: " DIST ", about " TIME "{{#roads}}, by {{roads}}{{/roads}}"
+ "{{#toll}}; with tolls{{/toll}}{{#ferry}}; with a ferry{{/ferry}}.\n"
+ "{{/alternatives}}\n"
+ "{{#n_steps}}\n"
+ "\nThe way, step by step:\n"
+ "{{/n_steps}}\n"
+ "{{#steps}}\n"
+ "{{@n}}. {{text}}{{#km}} ({{km}} km){{/km}}{{#m}} ({{m}} m){{/m}}\n"
+ "{{/steps}}\n"
+ "{{#cut}}\n"
+ "... and {{cut}} more steps.\n"
+ "{{/cut}}\n"
+ "{{#link}}\n"
+ "\nOn the map: {{link}}\n"
+ "{{/link}}\n"
+ "\nRoute: {{source}} on the servers of FOSSGIS; places: Nominatim; " OSM
+ ". Times are without traffic.\n"
+ "---\n"
+ "mode.car = by car\n"
+ "mode.bike = by bike\n"
+ "mode.foot = on foot\n" HOW_WORDS;
+
+const char MP_ROUTE_BRIEF[] =
+ "{{mode}} from {{from.name}}{{#from.how}} (where the user is, "
+ "{{from.how}}: say which place, and that it may be off){{/from.how}}"
+ "{{#via}} through {{via.name}}{{/via}} to {{to.name}}: {{#km}}{{km}} "
+ "km{{/km}}{{#m}}{{m}} m{{/m}}, {{#h}}{{h}} h {{/h}}{{min}} min without "
+ "traffic{{#roads}}, by {{roads}}{{/roads}}{{#toll}}, tolls{{/toll}}"
+ "{{#ferry}}, a ferry{{/ferry}}.{{#alternatives}} Another way: {{#km}}"
+ "{{km}} km{{/km}}, {{#h}}{{h}} h {{/h}}{{min}} min{{#roads}}, by "
+ "{{roads}}{{/roads}}.{{/alternatives}} The steps and the map's link are "
+ "shown to the user as they are: do not repeat them; answer in a line or "
+ "two from these figures, in the user's language.";
+
+/* The means of public transport, as Transitous names them. */
+#define MODE_WORDS \
+ "mode.BUS = bus\n" \
+ "mode.COACH = coach\n" \
+ "mode.TRAM = tram\n" \
+ "mode.SUBWAY = underground\n" \
+ "mode.METRO = metro\n" \
+ "mode.RAIL = train\n" \
+ "mode.HIGHSPEED_RAIL = high-speed train\n" \
+ "mode.LONG_DISTANCE = long-distance train\n" \
+ "mode.NIGHT_RAIL = night train\n" \
+ "mode.REGIONAL_FAST_RAIL = fast regional train\n" \
+ "mode.REGIONAL_RAIL = regional train\n" \
+ "mode.SUBURBAN = suburban train\n" \
+ "mode.FERRY = ferry\n" \
+ "mode.AIRPLANE = plane\n" \
+ "mode.FUNICULAR = funicular\n" \
+ "mode.AERIAL_LIFT = cable car\n" \
+ "mode.CABLE_CAR = cable tram\n" \
+ "mode.OTHER = other\n"
+
+const char MP_TRANSIT_LAYOUT[] =
+ "By public transport from " FROM " to {{to.name}}"
+ "{{#count}}; journeys found: {{count}}{{/count}}{{^count}}: no journey "
+ "found"
+ "{{/count}}.\n"
+ "{{#trips}}\n"
+ "\n{{@n}}. Leaves at " DEP ", arrives at " ARR
+ " ({{#h}}{{h}} h {{/h}}{{min}} min{{#transfers}}, changes: {{transfers}}"
+ "{{/transfers}}{{^transfers}}, direct{{/transfers}}):\n"
+ "{{#legs}}\n"
+ "{{#walk}} - walk " TIME "{{#km}}, {{km}} km{{/km}}{{#m}}, {{m}} m{{/m}} "
+ "to {{to}}\n"
+ "{{/walk}}{{^walk}} - {{dep.at}} {{mode|mode}} {{line}}{{#agency}} "
+ "({{agency}}){{/agency}}{{#headsign}} towards {{headsign}}{{/headsign}} "
+ "from {{from}}; {{arr.at}} get off at {{to}}{{#live}}, live times{{/live}}\n"
+ "{{/walk}}\n"
+ "{{/legs}}\n"
+ "{{#cut}}\n"
+ " ... and {{cut}} more legs.\n"
+ "{{/cut}}\n"
+ "{{/trips}}\n"
+ "\nTimes are local ({{tz}}) and from the timetables; those marked as live "
+ "times come from the operator in real time. "
+ "Source: Transitous (transitous.org), from the operators' open data; "
+ "places: Nominatim, " OSM ". Check the operator before you go.\n"
+ "---\n" MODE_WORDS DATE_WORDS HOW_WORDS;
+
+const char MP_TRANSIT_BRIEF[] =
+ "By public transport from {{from.name}}{{#from.how}} (where the user "
+ "is, {{from.how}}: say which place, and that it may be off){{/from.how}} "
+ "to {{to.name}}; journeys found: {{count}}. {{#trips}}{{@n}}: {{dep.at}}"
+ "{{#dep.date}} (day {{dep.day}}){{/dep.date}} to {{arr.at}}, {{#h}}{{h}} h "
+ "{{/h}}{{min}} min, changes: {{transfers}}; {{/trips}}The journeys, leg "
+ "by leg, are shown to the user as they are: do not repeat them; answer "
+ "in a line or two from these figures, in the user's language.";
+
+/* The kinds of place, as maps_nearby names them (nearby.c). */
+#define WHAT_WORDS \
+ "what.fuel = fuel stations\n" \
+ "what.charging = charging stations\n" \
+ "what.parking = car parks\n" \
+ "what.pharmacy = pharmacies\n" \
+ "what.hospital = hospitals\n" \
+ "what.doctor = doctors and clinics\n" \
+ "what.atm = cash machines\n" \
+ "what.bank = banks\n" \
+ "what.post_office = post offices\n" \
+ "what.police = police\n" \
+ "what.supermarket = supermarkets\n" \
+ "what.restaurant = restaurants\n" \
+ "what.cafe = cafés\n" \
+ "what.bar = bars and pubs\n" \
+ "what.hotel = hotels and guest houses\n" \
+ "what.toilets = public toilets\n" \
+ "what.train_station = railway stations\n" \
+ "what.bus_stop = bus stops\n" \
+ "what.museum = museums\n" \
+ "what.attraction = sights\n"
+
+const char MP_NEAR_LAYOUT[] =
+ "Within {{radius}} km of " AT ": {{found}} {{what|what}}"
+ "{{#count}}; these are the {{count}} nearest:{{/count}}{{^count}}.{{/count}}\n"
+ "{{#items}}\n"
+ "{{@n}}. {{#name}}{{name}}{{/name}}{{^name}}(no name){{/name}} - " DIST
+ "{{#dir}} {{dir|dir}}{{/dir}}{{#address}}; {{address}}{{/address}}"
+ "{{#hours}}; open: {{hours}}{{/hours}}{{#phone}}; {{phone}}{{/phone}}\n"
+ "{{/items}}\n"
+ "\nDistances as the crow flies. Opening hours as mapped, in "
+ "OpenStreetMap's notation: they may be out of date. Source: Overpass, "
+ "" OSM ".\n"
+ "---\n" WHAT_WORDS DIR_WORDS HOW_WORDS;
+
+const char MP_NEAR_BRIEF[] =
+ "{{found}} {{what}} within {{radius}} km of {{place.name}}{{#place.how}}"
+ " (where the user is, {{place.how}}: say which place, and that it may "
+ "be off){{/place.how}}{{#count}}; the nearest: {{#items}}{{name}} "
+ "{{#km}}{{km}} km{{/km}}{{#m}}{{m}} m{{/m}}; {{/items}}{{/count}}. The "
+ "list is shown to the user as it is: do not repeat it; answer in a line "
+ "or two, in the user's language.";
+
+const char MP_FIND_LAYOUT[] = AT ":\n"
+ "{{#place.address}}\n"
+ "- address: {{place.address}}\n"
+ "{{/place.address}}\n"
+ "- coordinates: {{place.lat}}, {{place.lon}}\n"
+ "{{#kind}}\n"
+ "- on the map as: {{kind}}\n"
+ "{{/kind}}\n"
+ "- on the map: {{link}}\n"
+ "\nSource: Nominatim, " OSM ".\n"
+ "---\n" HOW_WORDS;
+
+const char MP_FIND_BRIEF[] =
+ "{{place.name}}{{#place.how}} (where the user is, {{place.how}}: say "
+ "which place, and that it may be off){{/place.how}}: {{place.address}} "
+ "({{place.lat}}, {{place.lon}}). The address and a link to the map are "
+ "shown to the user as they are: do not repeat them; answer in a line, "
+ "in the user's language.";
diff --git a/src/maps/main.c b/src/maps/main.c
new file mode 100644
index 0000000..e007517
--- /dev/null
+++ b/src/maps/main.c
@@ -0,0 +1,77 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * main.c - janas-maps: roads and places as an MCP server over stdio, for
+ * janas-chat (which starts it by itself) and any other MCP client: routes
+ * by car, bike and on foot, journeys by public transport, what is near a
+ * place, where a place is. OpenStreetMap's data through free services,
+ * without a key.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "common/mcp_server.h"
+#include "maps.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+static const char INSTRUCTIONS[] =
+ "Use these tools by yourself when the user asks how to get somewhere, "
+ "how far or how long, by car, bike, on foot or by public transport, "
+ "where a place or an address is, or what is near (fuel, a pharmacy, a "
+ "cash machine...); never name them. Give places with their town. With "
+ "no start named, give none: the tool takes where the user is; tell the "
+ "user which place, and that it may be off. Times by road are without "
+ "traffic; public transport is from the timetables. Never ask the other "
+ "services for anything the user did not ask for.";
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "usage: janas-maps\n"
+ "An MCP server over stdio: a client starts it and calls its\n"
+ "tools - maps_route (a route by car, bike or on foot, step by\n"
+ "step), maps_transit (journeys by public transport),\n"
+ "maps_nearby (places of a kind near a place) and maps_find\n"
+ "(where a place or an address is).\n"
+ "Data, all free and without a key, from OpenStreetMap (ODbL):\n"
+ "Nominatim and Photon (places), Valhalla and OSRM on the\n"
+ "servers of FOSSGIS (routes), Transitous (public transport,\n"
+ "from the operators' open timetables), Overpass (what is\n"
+ "near). At most one request a second to each.\n"
+ "The servers can be changed: JANAS_NOMINATIM_URL,\n"
+ "JANAS_PHOTON_URL, JANAS_VALHALLA_URL, JANAS_OSRM_URL,\n"
+ "JANAS_TRANSITOUS_URL, JANAS_OVERPASS_URL,\n"
+ "JANAS_OVERPASS_URL2 (when the first is busy).\n"
+ "janas-chat starts it by itself when it is beside it.\n"
+ "Configured in a client as, for instance:\n"
+ " {\"mcpServers\": {\"maps\": {\"command\": "
+ "\"janas-maps\"}}}\n");
+}
+
+int main(int argc, char **argv)
+{
+ for (int i = 1; i < argc; i++) {
+ usage();
+ return strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 ? 0
+ : 2;
+ }
+ struct janas_mcps srv = {.name = "janas-maps",
+ .version = JANAS_VERSION,
+ .instructions = INSTRUCTIONS,
+ .tools_list = mp_tools_list,
+ .tools_call = mp_tools_call};
+ if (janas_mcps_open(&srv) != 0) {
+ fprintf(stderr, "janas-maps: cannot set its output aside\n");
+ return 1;
+ }
+ fprintf(stderr,
+ "janas-maps %s: ready, 4 tools (maps_route, maps_transit, "
+ "maps_nearby, maps_find)\n",
+ JANAS_VERSION);
+ janas_mcps_run(&srv);
+ mp_fetch_free();
+ return 0;
+}
diff --git a/src/maps/maps.h b/src/maps/maps.h
new file mode 100644
index 0000000..3189575
--- /dev/null
+++ b/src/maps/maps.h
@@ -0,0 +1,226 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * maps.h - janas-maps, roads and places as an MCP service: what its parts
+ * share. fetch.c asks the sources (one request a second to each, the
+ * answers kept a while), read.c reads their answers, place.c finds a place
+ * or an address, data.c writes what was read as the data of a layout,
+ * route.c, transit.c and nearby.c are the tools, layouts.c their layouts,
+ * tools.c lists them and takes their arguments.
+ *
+ * The sources are free and need no key: OpenStreetMap's data through
+ * Nominatim (places and addresses), Photon (when Nominatim does not
+ * answer), Valhalla and OSRM on the servers of FOSSGIS (routes by car, bike
+ * and on foot), Transitous (public transport) and Overpass (what is near).
+ * Each asks for a User-Agent naming the program and for at most one
+ * request a second; each address can be changed (JANAS_VALHALLA_URL and
+ * the like), as FOSSGIS asks.
+ */
+#ifndef JANAS_MAPS_H
+#define JANAS_MAPS_H
+
+#include <stddef.h>
+#include <time.h>
+
+#include "llm/json.h"
+
+/* ---- fetch.c ---- */
+
+/* GET of url, the body into out; answers of status 200 are kept keep_s
+ seconds and given again meanwhile; a host is asked at most once a
+ second. The HTTP status, or -1 with the reason in err. */
+int mp_fetch(const char *url, int keep_s, struct janas_buf *out, char *err,
+ size_t err_len);
+/* The same, waiting at most timeout_ms for each part of the answer
+ (mp_fetch: 15 s). */
+int mp_fetch_ms(const char *url, int keep_s, int timeout_ms,
+ struct janas_buf *out, char *err, size_t err_len);
+void mp_fetch_free(void);
+
+/* The address of a source: the variable env when set, else def. */
+const char *mp_base(const char *env, const char *def);
+
+/* s into b, as a URL's query wants it. */
+void mp_url_put(struct janas_buf *b, const char *s);
+
+/* The language of the answers: the computer's (LANG=it_IT.UTF-8: "it"),
+ else "en". */
+const char *mp_lang(void);
+
+/* ---- read.c: the sources' answers ---- */
+
+struct mp_place {
+ char name[128]; /* "Stazione Centrale", "Trapani" */
+ char address[256]; /* "Stazione Centrale, Via Paolo Balsamo, ..." */
+ char city[96]; /* "Palermo"; "" when not known */
+ char kind[64]; /* "railway station" (OSM's class and type) */
+ char osm[48]; /* "node/123", for a link; "" */
+ double lat, lon;
+ char how[96]; /* where the user is, when the place was not named: how it
+ was told (locate.h); "" otherwise */
+};
+
+/* The first place of Nominatim's or Photon's answer: 0, or -1 when none. */
+int mp_read_nominatim(const char *text, size_t n, struct mp_place *p);
+int mp_read_photon(const char *text, size_t n, struct mp_place *p);
+
+#define MP_STEPS 160
+#define MP_ROUTES 3
+
+struct mp_step {
+ char text[200]; /* the source's, in its language */
+ double km;
+};
+
+struct mp_route {
+ double km, min;
+ int toll, highway, ferry;
+ char roads[160]; /* the longest roads, "A29, SS113" */
+ struct mp_step *step; /* the first route's only; NULL for the others */
+ int n_step, cut; /* cut: steps left out (more than MP_STEPS) */
+};
+
+struct mp_routes {
+ const char *source; /* "Valhalla", "OSRM" */
+ struct mp_route r[MP_ROUTES];
+ int n;
+};
+
+/* Valhalla's /route answer (with its alternates), OSRM's: 0, or -1 with
+ the reason in err. The steps are malloc'd: mp_routes_free. */
+int mp_read_valhalla(const char *text, size_t n, struct mp_routes *rs,
+ char *err, size_t err_len);
+int mp_read_osrm(const char *text, size_t n, struct mp_routes *rs, char *err,
+ size_t err_len);
+void mp_routes_free(struct mp_routes *rs);
+
+#define MP_TRIPS 5
+#define MP_LEGS 12
+
+struct mp_leg {
+ char mode[24]; /* "WALK", "BUS", "REGIONAL_RAIL" */
+ char line[64]; /* "REG 21854", "101" */
+ char agency[64]; /* "TRENITALIA" */
+ char headsign[96];
+ char from[96], to[96];
+ time_t dep, arr;
+ double walk_m;
+ int real_time;
+};
+
+struct mp_trip {
+ time_t dep, arr;
+ int transfers;
+ struct mp_leg leg[MP_LEGS];
+ int n_leg, cut;
+};
+
+struct mp_transit {
+ struct mp_trip t[MP_TRIPS];
+ int n;
+ char tz[48]; /* the start's zone, "Europe/Rome" */
+};
+
+/* Transitous' /api/v1/plan answer: 0, or -1 with the reason in err. */
+int mp_read_transit(const char *text, size_t n, struct mp_transit *tr,
+ char *err, size_t err_len);
+
+#define MP_NEAR 20
+
+struct mp_poi {
+ char name[128];
+ char address[160];
+ char hours[128]; /* OSM's opening_hours, as written */
+ char phone[48];
+ char osm[48]; /* "node/123" */
+ double lat, lon, m;
+};
+
+struct mp_near {
+ struct mp_poi p[MP_NEAR];
+ int n, found; /* listed, and found within the radius */
+};
+
+/* Overpass' answer, the nearest to (lat, lon) first, at most max. 0, or -1
+ with the reason in err. */
+int mp_read_overpass(const char *text, size_t n, double lat, double lon,
+ int max, struct mp_near *nr, char *err, size_t err_len);
+
+/* UTC "2026-10-02T03:42:00Z" as a time, or -1. */
+time_t mp_utc(const char *s);
+
+/* ---- place.c ---- */
+
+/* A place or an address by its name ("Via Fardella, Trapani", "Colosseo"),
+ or "lat,lon": the nearest to (near_lat, near_lon) when given, preferred.
+ 0, or -1 with the reason in err. */
+int mp_place_find(const char *query, double near_lat, double near_lon,
+ struct mp_place *p, char *err, size_t err_len);
+/* A point named from the built-in tables ("3 km N of Palermo"). */
+void mp_place_at(double lat, double lon, struct mp_place *p);
+/* What is at a point, from Nominatim: its name and address. 0, or -1 (p
+ untouched). */
+int mp_place_reverse(double lat, double lon, struct mp_place *p);
+
+/* ---- data.c: the data of the layouts ---- */
+
+void mp_jstr(struct janas_buf *b, const char *key, const char *v);
+void mp_jnum(struct janas_buf *b, const char *key, double v, int decimals);
+/* a place: "name", "address", "how"... as an object under key */
+void mp_jplace(struct janas_buf *b, const char *key, const struct mp_place *p);
+/* minutes as "h" and "min" */
+void mp_jtime(struct janas_buf *b, double min);
+/* a time in the zone tz: "at" ("08:42") and, when not today, "date" with
+ "wd", "day", "mon", under key */
+void mp_jclock(struct janas_buf *b, const char *key, time_t t, const char *tz);
+void mp_route_data(struct janas_buf *d, const struct mp_place *from,
+ const struct mp_place *via, const struct mp_place *to,
+ const char *mode, const struct mp_routes *rs);
+void mp_transit_data(struct janas_buf *d, const struct mp_place *from,
+ const struct mp_place *to, const struct mp_transit *tr);
+void mp_near_data(struct janas_buf *d, const struct mp_place *at,
+ const char *what, double radius_km, const struct mp_near *nr);
+void mp_find_data(struct janas_buf *d, const struct mp_place *p);
+
+/* ---- tools.c ---- */
+
+void mp_tools_list(void *ctx, struct janas_buf *b);
+int mp_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b);
+
+const char *mp_arg_str(const struct janas_json *args, const char *name);
+double mp_arg_num(const struct janas_json *args, const char *name, double def);
+int mp_arg_bool(const struct janas_json *args, const char *name, int def);
+/* The place of argument name: named, or where the user is when it is not
+ and here is set. 0; -1 with an error result already in b. */
+int mp_arg_place(const struct janas_json *args, const char *name, int here,
+ double near_lat, double near_lon, struct mp_place *p,
+ struct janas_buf *b);
+/* A text result, out freed. */
+int mp_result(struct janas_buf *out, struct janas_buf *b, int is_error);
+/* The answer from the data and its layout (d freed). */
+int mp_answer(struct janas_buf *b, const char *name, struct janas_buf *d,
+ const char *layout, const char *brief);
+
+int mp_tool_route(const struct janas_json *args, struct janas_buf *b);
+int mp_tool_transit(const struct janas_json *args, struct janas_buf *b);
+int mp_tool_nearby(const struct janas_json *args, struct janas_buf *b);
+int mp_tool_find(const struct janas_json *args, struct janas_buf *b);
+
+/* ---- nearby.c ---- */
+
+/* The kinds of place maps_nearby looks for: name, OSM filter. */
+struct mp_kind {
+ const char *name, *filter;
+};
+extern const struct mp_kind MP_KINDS[];
+extern const size_t MP_N_KINDS;
+
+/* ---- layouts.c ---- */
+
+extern const char MP_ROUTE_LAYOUT[], MP_ROUTE_BRIEF[];
+extern const char MP_TRANSIT_LAYOUT[], MP_TRANSIT_BRIEF[];
+extern const char MP_NEAR_LAYOUT[], MP_NEAR_BRIEF[];
+extern const char MP_FIND_LAYOUT[], MP_FIND_BRIEF[];
+
+#endif
diff --git a/src/maps/nearby.c b/src/maps/nearby.c
new file mode 100644
index 0000000..f11c1fb
--- /dev/null
+++ b/src/maps/nearby.c
@@ -0,0 +1,113 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * nearby.c - maps_nearby (see maps.h): the places of a kind around a
+ * point, from OpenStreetMap through Overpass, nearest first. The kinds are
+ * a short list, each a filter of OSM's tags, so that the model picks one
+ * and never writes a query.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "maps.h"
+
+#define NEAR_KEEP_S 3600
+#define NEAR_LIST 10
+/* Overpass may take its 20 s; two servers asked within the minute
+ janas-chat waits for a tool */
+#define NEAR_WAIT_MS 25000
+
+const struct mp_kind MP_KINDS[] = {
+ {"fuel", "[amenity=fuel]"},
+ {"charging", "[amenity=charging_station]"},
+ {"parking", "[amenity=parking]"},
+ {"pharmacy", "[amenity=pharmacy]"},
+ {"hospital", "[amenity=hospital]"},
+ {"doctor", "[amenity~\"^(doctors|clinic)$\"]"},
+ {"atm", "[amenity=atm]"},
+ {"bank", "[amenity=bank]"},
+ {"post_office", "[amenity=post_office]"},
+ {"police", "[amenity=police]"},
+ {"supermarket", "[shop=supermarket]"},
+ {"restaurant", "[amenity=restaurant]"},
+ {"cafe", "[amenity=cafe]"},
+ {"bar", "[amenity~\"^(bar|pub)$\"]"},
+ {"hotel", "[tourism~\"^(hotel|guest_house|hostel|motel)$\"]"},
+ {"toilets", "[amenity=toilets]"},
+ {"train_station", "[railway=station]"},
+ {"bus_stop", "[highway=bus_stop]"},
+ {"museum", "[tourism=museum]"},
+ {"attraction", "[tourism~\"^(attraction|viewpoint)$\"]"},
+};
+const size_t MP_N_KINDS = sizeof MP_KINDS / sizeof *MP_KINDS;
+
+int mp_tool_nearby(const struct janas_json *args, struct janas_buf *b)
+{
+ const char *what = mp_arg_str(args, "what");
+ const struct mp_kind *k = NULL;
+ for (size_t i = 0; what && i < MP_N_KINDS; i++)
+ if (strcmp(what, MP_KINDS[i].name) == 0)
+ k = &MP_KINDS[i];
+ if (!k) {
+ struct janas_buf out = {0};
+ janas_buf_puts(&out, "Give what to look for, one of:");
+ for (size_t i = 0; i < MP_N_KINDS; i++)
+ janas_buf_printf(&out, " %s", MP_KINDS[i].name);
+ janas_buf_puts(&out, ".");
+ return mp_result(&out, b, 1);
+ }
+ struct mp_place at;
+ if (mp_arg_place(args, "place", 1, NAN, NAN, &at, b) != 0)
+ return 0;
+ double r = mp_arg_num(args, "radius", 2);
+ r = isnan(r) ? 2 : fmin(10, fmax(0.1, r));
+ struct janas_buf q = {0};
+ janas_buf_printf(&q,
+ "[out:json][timeout:20];nwr%s(around:%.0f,%.6f,%.6f);"
+ "out center tags 300;",
+ k->filter, r * 1000, at.lat, at.lon);
+ janas_buf_put(&q, "", 1);
+ /* FOSSGIS's instance first; when it is busy or down, Private.coffee's
+ ("Feel free to use our service in any project, there is no rate
+ limit in place", OSM wiki, 2 Oct 2026) */
+ const char *base[2] = {
+ mp_base("JANAS_OVERPASS_URL",
+ "https://overpass-api.de/api/interpreter"),
+ mp_base("JANAS_OVERPASS_URL2",
+ "https://overpass.private.coffee/api/interpreter")};
+ char err[2][300] = {"", ""};
+ struct mp_near nr;
+ int ok = 0, t;
+ for (t = 0; t < 2 && !ok && !q.oom; t++) {
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(&url, "%s?data=", base[t]);
+ mp_url_put(&url, q.p);
+ int status = url.oom ? -1
+ : mp_fetch_ms(url.p, NEAR_KEEP_S, NEAR_WAIT_MS,
+ &body, err[t], sizeof err[t]);
+ ok = status == 200 &&
+ mp_read_overpass(body.p, body.n, at.lat, at.lon, NEAR_LIST, &nr,
+ err[t], sizeof err[t]) == 0;
+ const char *host = strstr(base[t], "://");
+ host = host ? host + 3 : base[t];
+ if (status > 0 && status != 200)
+ snprintf(err[t], sizeof err[t], "Overpass at %.*s: HTTP %d%s",
+ (int)strcspn(host, "/"), host, status,
+ status == 429 || status == 504 ? " (busy)" : "");
+ janas_buf_free(&url);
+ janas_buf_free(&body);
+ }
+ janas_buf_free(&q);
+ if (!ok) {
+ struct janas_buf out = {0};
+ janas_buf_printf(&out, "Nothing could be looked up near %s: %s%s%s",
+ at.name, err[0], t > 1 ? "; " : "",
+ t > 1 ? err[1] : "");
+ janas_buf_puts(&out, ". Try again in a minute.");
+ return mp_result(&out, b, 1);
+ }
+ struct janas_buf d = {0};
+ mp_near_data(&d, &at, k->name, r, &nr);
+ return mp_answer(b, "maps_nearby", &d, MP_NEAR_LAYOUT, MP_NEAR_BRIEF);
+}
diff --git a/src/maps/place.c b/src/maps/place.c
new file mode 100644
index 0000000..116e38f
--- /dev/null
+++ b/src/maps/place.c
@@ -0,0 +1,162 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * place.c - a place or an address by its name (see maps.h): Nominatim,
+ * OpenStreetMap's own search, which knows streets, buildings and stations
+ * as well as towns; Photon when it does not answer; a point named from the
+ * tables built into the program.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common/geo.h"
+#include "maps.h"
+
+#define DEG(x) ((x) * 1e-5)
+#define PLACE_KEEP_S (7 * 24 * 3600) /* places do not move */
+
+void mp_place_at(double lat, double lon, struct mp_place *p)
+{
+ memset(p, 0, sizeof *p);
+ p->lat = lat;
+ p->lon = lon;
+ double km;
+ const struct geo_city *c = geo_city_near(lat, lon, &km);
+ if (!c)
+ snprintf(p->name, sizeof p->name, "%.5f, %.5f", lat, lon);
+ else if (km < 3)
+ snprintf(p->name, sizeof p->name, "%s", c->name);
+ else
+ snprintf(p->name, sizeof p->name, "%.0f km %s of %s", km,
+ geo_compass(geo_bearing(DEG(c->lat), DEG(c->lon), lat, lon)),
+ c->name);
+ if (c)
+ snprintf(p->city, sizeof p->city, "%s", c->name);
+}
+
+/* "38.02, 12.51" */
+static int as_point(const char *q, double *lat, double *lon)
+{
+ char *end;
+ double a = strtod(q, &end);
+ if (end == q)
+ return 0;
+ while (*end == ' ' || *end == ',' || *end == ';')
+ end++;
+ char *end2;
+ double b = strtod(end, &end2);
+ while (*end2 == ' ')
+ end2++;
+ if (end2 == end || *end2 || fabs(a) > 90 || fabs(b) > 180)
+ return 0;
+ *lat = a;
+ *lon = b;
+ return 1;
+}
+
+static int nominatim(const char *q, double near_lat, double near_lon,
+ struct mp_place *p, char *why, size_t why_len)
+{
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(
+ &url, "%s/search?q=",
+ mp_base("JANAS_NOMINATIM_URL", "https://nominatim.openstreetmap.org"));
+ mp_url_put(&url, q);
+ janas_buf_printf(&url,
+ "&format=jsonv2&limit=5&addressdetails=1&"
+ "accept-language=%s",
+ mp_lang());
+ /* a place near the other end preferred, not required: "Stazione
+ Centrale" on the way from Trapani is Palermo's */
+ if (!isnan(near_lat) && !isnan(near_lon))
+ janas_buf_printf(&url, "&viewbox=%.4f,%.4f,%.4f,%.4f&bounded=0",
+ near_lon - 1, near_lat + 1, near_lon + 1,
+ near_lat - 1);
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, PLACE_KEEP_S, &body, why, why_len);
+ janas_buf_free(&url);
+ int rc = status == 200 ? mp_read_nominatim(body.p, body.n, p) : -1;
+ if (status > 0 && status != 200)
+ snprintf(why, why_len, "Nominatim: HTTP %d", status);
+ janas_buf_free(&body);
+ return rc;
+}
+
+static int photon(const char *q, double near_lat, double near_lon,
+ struct mp_place *p, char *why, size_t why_len)
+{
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(&url, "%s/api/?q=",
+ mp_base("JANAS_PHOTON_URL", "https://photon.komoot.io"));
+ mp_url_put(&url, q);
+ janas_buf_puts(&url, "&limit=1");
+ if (!isnan(near_lat) && !isnan(near_lon))
+ janas_buf_printf(&url, "&lat=%.4f&lon=%.4f", near_lat, near_lon);
+ /* its languages are few: else the names of the place's own */
+ const char *l = mp_lang();
+ if (strcmp(l, "de") == 0 || strcmp(l, "en") == 0 || strcmp(l, "fr") == 0)
+ janas_buf_printf(&url, "&lang=%s", l);
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, PLACE_KEEP_S, &body, why, why_len);
+ janas_buf_free(&url);
+ int rc = status == 200 ? mp_read_photon(body.p, body.n, p) : -1;
+ if (status > 0 && status != 200)
+ snprintf(why, why_len, "Photon: HTTP %d", status);
+ janas_buf_free(&body);
+ return rc;
+}
+
+int mp_place_reverse(double lat, double lon, struct mp_place *p)
+{
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(
+ &url,
+ "%s/reverse?lat=%.6f&lon=%.6f&format=jsonv2&"
+ "addressdetails=1&accept-language=%s",
+ mp_base("JANAS_NOMINATIM_URL", "https://nominatim.openstreetmap.org"),
+ lat, lon, mp_lang());
+ char why[256];
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, PLACE_KEEP_S, &body, why, sizeof why);
+ janas_buf_free(&url);
+ struct mp_place q;
+ int rc = status == 200 ? mp_read_nominatim(body.p, body.n, &q) : -1;
+ janas_buf_free(&body);
+ if (rc == 0) { /* the point asked, named as what is there */
+ q.lat = lat;
+ q.lon = lon;
+ *p = q;
+ }
+ return rc;
+}
+
+int mp_place_find(const char *query, double near_lat, double near_lon,
+ struct mp_place *p, char *err, size_t err_len)
+{
+ while (*query == ' ')
+ query++;
+ if (!*query) {
+ snprintf(err, err_len, "no place given");
+ return -1;
+ }
+ double lat, lon;
+ if (as_point(query, &lat, &lon)) {
+ mp_place_at(lat, lon, p);
+ return 0;
+ }
+ char w1[256] = "", w2[256] = "";
+ if (nominatim(query, near_lat, near_lon, p, w1, sizeof w1) == 0)
+ return 0;
+ /* Nominatim knew nothing: Photon will not know more */
+ if (!w1[0]) {
+ snprintf(err, err_len, "no place called \"%s\" found", query);
+ return -1;
+ }
+ if (photon(query, near_lat, near_lon, p, w2, sizeof w2) == 0)
+ return 0;
+ snprintf(err, err_len, "no place called \"%s\" found (%s%s%s)", query, w1,
+ w2[0] ? "; " : "", w2);
+ return -1;
+}
diff --git a/src/maps/read.c b/src/maps/read.c
new file mode 100644
index 0000000..6639f93
--- /dev/null
+++ b/src/maps/read.c
@@ -0,0 +1,548 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * read.c - janas-maps reads its sources' answers (see maps.h): Nominatim's
+ * and Photon's places, Valhalla's and OSRM's routes, Transitous' journeys,
+ * Overpass' places around a point. No network here, so that the tests can
+ * read answers kept as they came.
+ */
+#define _GNU_SOURCE /* timegm */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/geo.h"
+#include "maps.h"
+
+static void copy(char *to, size_t cap, const char *s)
+{
+ snprintf(to, cap, "%s", s ? s : "");
+}
+
+static const char *str(const struct janas_json *o, const char *key)
+{
+ const char *s = janas_json_str(janas_json_get(o, key));
+ return s && *s ? s : NULL;
+}
+
+/* a number given as a number or as a text (Nominatim's "38.02") */
+static double num(const struct janas_json *o, const char *key)
+{
+ const struct janas_json *v = janas_json_get(o, key);
+ if (v && v->type == JANAS_JSON_STRING) {
+ char *end;
+ double d = strtod(v->s, &end);
+ return end > v->s ? d : NAN;
+ }
+ return janas_json_num(v, NAN);
+}
+
+static struct janas_json_doc *parse(const char *text, size_t n, const char *who,
+ char *err, size_t err_len)
+{
+ char why[128];
+ struct janas_json_doc *d = janas_json_parse(text, n, why, sizeof why);
+ if (!d && err)
+ snprintf(err, err_len, "%s: an answer it could not read (%s)", who,
+ why);
+ return d;
+}
+
+time_t mp_utc(const char *s)
+{
+ struct tm tm = {0};
+ if (!s || sscanf(s, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon,
+ &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) < 5)
+ return -1;
+ tm.tm_year -= 1900;
+ tm.tm_mon -= 1;
+ return timegm(&tm);
+}
+
+/* ---- places ---- */
+
+/* "Via Paolo Balsamo 12": the road and the number */
+static void street(char *to, size_t cap, const char *road, const char *number)
+{
+ if (road && number)
+ snprintf(to, cap, "%s %s", road, number);
+ else
+ copy(to, cap, road);
+}
+
+/* A town's boundary has its point in the middle of the municipality's
+ land: Trapani's in the fields 25 km from the town. The town itself, a
+ place of the same name within 40 km among the answers, gives the point
+ instead. */
+static const struct janas_json *town_of(const struct janas_json *f)
+{
+ if (!janas_json_is(janas_json_get(f, "category"), "boundary"))
+ return f;
+ const char *name = str(f, "name");
+ for (const struct janas_json *g = f->next; g && name; g = g->next) {
+ const char *gn = str(g, "name");
+ if (janas_json_is(janas_json_get(g, "category"), "place") && gn &&
+ strcmp(gn, name) == 0 &&
+ geo_km(num(f, "lat"), num(f, "lon"), num(g, "lat"), num(g, "lon")) <
+ 40)
+ return g;
+ }
+ return f;
+}
+
+int mp_read_nominatim(const char *text, size_t n, struct mp_place *p)
+{
+ struct janas_json_doc *d = parse(text, n, "Nominatim", NULL, 0);
+ const struct janas_json *r = d ? janas_json_root(d) : NULL;
+ /* a search answers a list, a reverse lookup one place */
+ const struct janas_json *f = !r ? NULL
+ : r->type == JANAS_JSON_ARRAY ? r->child
+ : r->type == JANAS_JSON_OBJECT ? r
+ : NULL;
+ int ok = f && !isnan(num(f, "lat")) && !isnan(num(f, "lon"));
+ if (ok) {
+ memset(p, 0, sizeof *p);
+ const struct janas_json *a = janas_json_get(f, "address");
+ const char *city = str(a, "city");
+ if (!city)
+ city = str(a, "town");
+ if (!city)
+ city = str(a, "village");
+ if (!city)
+ city = str(a, "municipality");
+ const char *name = str(f, "name");
+ if (name)
+ copy(p->name, sizeof p->name, name);
+ else
+ street(p->name, sizeof p->name, str(a, "road"),
+ str(a, "house_number"));
+ if (!p->name[0])
+ copy(p->name, sizeof p->name, city);
+ copy(p->address, sizeof p->address, str(f, "display_name"));
+ copy(p->city, sizeof p->city, city);
+ const char *cat = str(f, "category"), *type = str(f, "type");
+ if (cat && type)
+ snprintf(p->kind, sizeof p->kind, "%s=%s", cat, type);
+ const char *ot = str(f, "osm_type");
+ double id = num(f, "osm_id");
+ if (ot && !isnan(id))
+ snprintf(p->osm, sizeof p->osm, "%s/%.0f", ot, id);
+ const struct janas_json *t = town_of(f);
+ p->lat = num(t, "lat");
+ p->lon = num(t, "lon");
+ }
+ janas_json_free(d);
+ return ok ? 0 : -1;
+}
+
+int mp_read_photon(const char *text, size_t n, struct mp_place *p)
+{
+ struct janas_json_doc *d = parse(text, n, "Photon", NULL, 0);
+ const struct janas_json *fs =
+ d ? janas_json_get(janas_json_root(d), "features") : NULL;
+ const struct janas_json *f =
+ fs && fs->type == JANAS_JSON_ARRAY ? fs->child : NULL;
+ const struct janas_json *c =
+ janas_json_get(janas_json_get(f, "geometry"), "coordinates");
+ const struct janas_json *lon =
+ c && c->type == JANAS_JSON_ARRAY ? c->child : NULL;
+ const struct janas_json *lat = lon ? lon->next : NULL;
+ int ok =
+ lat && lat->type == JANAS_JSON_NUMBER && lon->type == JANAS_JSON_NUMBER;
+ if (ok) {
+ memset(p, 0, sizeof *p);
+ const struct janas_json *q = janas_json_get(f, "properties");
+ char road[128];
+ street(road, sizeof road, str(q, "street"), str(q, "housenumber"));
+ const char *name = str(q, "name"), *city = str(q, "city");
+ copy(p->name, sizeof p->name, name ? name : road[0] ? road : city);
+ copy(p->city, sizeof p->city, city);
+ struct janas_buf a = {0};
+ const char *parts[] = {name, road[0] ? road : NULL, str(q, "postcode"),
+ city, str(q, "state"), str(q, "country")};
+ for (size_t i = 0; i < sizeof parts / sizeof *parts; i++)
+ if (parts[i])
+ janas_buf_printf(&a, "%s%s", a.n ? ", " : "", parts[i]);
+ copy(p->address, sizeof p->address, a.p);
+ janas_buf_free(&a);
+ const char *k = str(q, "osm_key"), *v = str(q, "osm_value");
+ if (k && v)
+ snprintf(p->kind, sizeof p->kind, "%s=%s", k, v);
+ const char *ot = str(q, "osm_type");
+ double id = num(q, "osm_id");
+ if (ot && !isnan(id))
+ snprintf(p->osm, sizeof p->osm, "%s/%.0f",
+ *ot == 'N' ? "node"
+ : *ot == 'W' ? "way"
+ : "relation",
+ id);
+ p->lat = janas_json_num(lat, 0);
+ p->lon = janas_json_num(lon, 0);
+ }
+ janas_json_free(d);
+ return ok ? 0 : -1;
+}
+
+/* ---- routes ---- */
+
+#define N_ROADS 64
+
+struct roads {
+ char name[N_ROADS][64];
+ double km[N_ROADS];
+ int n;
+};
+
+/* A way's name for the roads taken: its own number before the European
+ route's (A29, not E 90), when it has both. */
+static const char *road_name(const struct janas_json *names)
+{
+ const char *first = NULL;
+ for (const struct janas_json *s =
+ names && names->type == JANAS_JSON_ARRAY ? names->child : NULL;
+ s; s = s->next) {
+ const char *t = janas_json_str(s);
+ if (!t || !*t)
+ continue;
+ if (!first)
+ first = t;
+ if (!(t[0] == 'E' && t[1] == ' '))
+ return t;
+ }
+ return first;
+}
+
+static void road_add(struct roads *r, const char *name, double km)
+{
+ if (!name)
+ return;
+ for (int i = 0; i < r->n; i++)
+ if (strcmp(r->name[i], name) == 0) {
+ r->km[i] += km;
+ return;
+ }
+ if (r->n < N_ROADS) {
+ copy(r->name[r->n], sizeof r->name[r->n], name);
+ r->km[r->n++] = km;
+ }
+}
+
+/* the three longest, in the order they are driven */
+static void roads_line(const struct roads *r, char *out, size_t cap)
+{
+ int pick[3], np = 0;
+ for (int k = 0; k < 3; k++) {
+ int best = -1;
+ for (int i = 0; i < r->n; i++) {
+ int taken = 0;
+ for (int j = 0; j < np; j++)
+ taken |= pick[j] == i;
+ if (!taken && r->km[i] >= 1 && (best < 0 || r->km[i] > r->km[best]))
+ best = i;
+ }
+ if (best < 0)
+ break;
+ pick[np++] = best;
+ }
+ for (int i = 0; i < np; i++) /* by the order of first meeting */
+ for (int j = i + 1; j < np; j++)
+ if (pick[j] < pick[i]) {
+ int t = pick[i];
+ pick[i] = pick[j];
+ pick[j] = t;
+ }
+ out[0] = 0;
+ for (int i = 0; i < np; i++) {
+ size_t n = strlen(out);
+ snprintf(out + n, cap - n, "%s%s", i ? ", " : "", r->name[pick[i]]);
+ }
+}
+
+static int valhalla_trip(const struct janas_json *trip, struct mp_route *r,
+ int steps)
+{
+ const struct janas_json *sum = janas_json_get(trip, "summary");
+ r->km = janas_json_num(janas_json_get(sum, "length"), NAN);
+ r->min = janas_json_num(janas_json_get(sum, "time"), NAN) / 60;
+ if (isnan(r->km) || isnan(r->min))
+ return -1;
+ r->toll = janas_json_get(sum, "has_toll") &&
+ janas_json_get(sum, "has_toll")->type == JANAS_JSON_TRUE;
+ r->highway = janas_json_get(sum, "has_highway") &&
+ janas_json_get(sum, "has_highway")->type == JANAS_JSON_TRUE;
+ r->ferry = janas_json_get(sum, "has_ferry") &&
+ janas_json_get(sum, "has_ferry")->type == JANAS_JSON_TRUE;
+ struct roads *rd = calloc(1, sizeof *rd);
+ if (steps)
+ r->step = calloc(MP_STEPS, sizeof *r->step);
+ const struct janas_json *legs = janas_json_get(trip, "legs");
+ for (const struct janas_json *l =
+ legs && legs->type == JANAS_JSON_ARRAY ? legs->child : NULL;
+ l; l = l->next) {
+ const struct janas_json *ms = janas_json_get(l, "maneuvers");
+ for (const struct janas_json *m =
+ ms && ms->type == JANAS_JSON_ARRAY ? ms->child : NULL;
+ m; m = m->next) {
+ double km = janas_json_num(janas_json_get(m, "length"), 0);
+ if (rd)
+ road_add(rd, road_name(janas_json_get(m, "street_names")), km);
+ const char *t = str(m, "instruction");
+ if (!t || !r->step)
+ continue;
+ if (r->n_step < MP_STEPS) {
+ copy(r->step[r->n_step].text, sizeof r->step[0].text, t);
+ r->step[r->n_step++].km = km;
+ } else {
+ r->cut++;
+ }
+ }
+ }
+ if (rd)
+ roads_line(rd, r->roads, sizeof r->roads);
+ free(rd);
+ return 0;
+}
+
+int mp_read_valhalla(const char *text, size_t n, struct mp_routes *rs,
+ char *err, size_t err_len)
+{
+ memset(rs, 0, sizeof *rs);
+ rs->source = "Valhalla";
+ struct janas_json_doc *d = parse(text, n, "Valhalla", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *root = janas_json_root(d);
+ const struct janas_json *trip = janas_json_get(root, "trip");
+ int rc = -1;
+ if (!trip) {
+ const char *e = str(root, "error");
+ snprintf(err, err_len, "Valhalla: %s", e ? e : "no route");
+ } else if (valhalla_trip(trip, &rs->r[0], 1) != 0) {
+ snprintf(err, err_len, "Valhalla: a route without its length");
+ } else {
+ rs->n = 1;
+ const struct janas_json *alt = janas_json_get(root, "alternates");
+ for (const struct janas_json *a =
+ alt && alt->type == JANAS_JSON_ARRAY ? alt->child : NULL;
+ a && rs->n < MP_ROUTES; a = a->next)
+ if (valhalla_trip(janas_json_get(a, "trip"), &rs->r[rs->n], 0) == 0)
+ rs->n++;
+ rc = 0;
+ }
+ janas_json_free(d);
+ return rc;
+}
+
+int mp_read_osrm(const char *text, size_t n, struct mp_routes *rs, char *err,
+ size_t err_len)
+{
+ memset(rs, 0, sizeof *rs);
+ rs->source = "OSRM";
+ struct janas_json_doc *d = parse(text, n, "OSRM", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *root = janas_json_root(d);
+ const struct janas_json *routes = janas_json_get(root, "routes");
+ if (!janas_json_is(janas_json_get(root, "code"), "Ok") || !routes ||
+ routes->type != JANAS_JSON_ARRAY) {
+ const char *m = str(root, "message");
+ snprintf(err, err_len, "OSRM: %s", m ? m : "no route");
+ janas_json_free(d);
+ return -1;
+ }
+ /* a place far from any road it knows (its map is Europe's): OSRM
+ takes the nearest road all the same: New York's, 5,535 km away */
+ const struct janas_json *wps = janas_json_get(root, "waypoints");
+ for (const struct janas_json *w =
+ wps && wps->type == JANAS_JSON_ARRAY ? wps->child : NULL;
+ w; w = w->next) {
+ double m = janas_json_num(janas_json_get(w, "distance"), 0);
+ if (m > 5000) {
+ snprintf(err, err_len,
+ "OSRM: a place is %.0f km from the nearest road it "
+ "knows (its map covers Europe)",
+ m / 1000);
+ janas_json_free(d);
+ return -1;
+ }
+ }
+ for (const struct janas_json *r = routes->child; r && rs->n < MP_ROUTES;
+ r = r->next) {
+ struct mp_route *o = &rs->r[rs->n];
+ o->km = janas_json_num(janas_json_get(r, "distance"), NAN) / 1000;
+ o->min = janas_json_num(janas_json_get(r, "duration"), NAN) / 60;
+ if (isnan(o->km) || isnan(o->min))
+ continue;
+ const struct janas_json *legs = janas_json_get(r, "legs");
+ for (const struct janas_json *l =
+ legs && legs->type == JANAS_JSON_ARRAY ? legs->child : NULL;
+ l; l = l->next) {
+ const char *s = str(l, "summary");
+ size_t k = strlen(o->roads);
+ if (s && k + 3 < sizeof o->roads)
+ snprintf(o->roads + k, sizeof o->roads - k, "%s%s",
+ k ? ", " : "", s);
+ }
+ rs->n++;
+ }
+ janas_json_free(d);
+ if (!rs->n) {
+ snprintf(err, err_len, "OSRM: no route");
+ return -1;
+ }
+ return 0;
+}
+
+void mp_routes_free(struct mp_routes *rs)
+{
+ for (int i = 0; i < MP_ROUTES; i++) {
+ free(rs->r[i].step);
+ rs->r[i].step = NULL;
+ }
+}
+
+/* ---- public transport ---- */
+
+static void leg_place(char *to, size_t cap, const struct janas_json *p)
+{
+ copy(to, cap, str(p, "name"));
+}
+
+int mp_read_transit(const char *text, size_t n, struct mp_transit *tr,
+ char *err, size_t err_len)
+{
+ memset(tr, 0, sizeof *tr);
+ struct janas_json_doc *d = parse(text, n, "Transitous", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *root = janas_json_root(d);
+ const struct janas_json *its = janas_json_get(root, "itineraries");
+ for (const struct janas_json *it =
+ its && its->type == JANAS_JSON_ARRAY ? its->child : NULL;
+ it && tr->n < MP_TRIPS; it = it->next) {
+ struct mp_trip *t = &tr->t[tr->n];
+ memset(t, 0, sizeof *t);
+ t->dep = mp_utc(str(it, "startTime"));
+ t->arr = mp_utc(str(it, "endTime"));
+ t->transfers = (int)janas_json_num(janas_json_get(it, "transfers"), 0);
+ if (t->dep < 0 || t->arr < 0)
+ continue;
+ const struct janas_json *legs = janas_json_get(it, "legs");
+ for (const struct janas_json *l =
+ legs && legs->type == JANAS_JSON_ARRAY ? legs->child : NULL;
+ l; l = l->next) {
+ if (t->n_leg == MP_LEGS) {
+ t->cut++;
+ continue;
+ }
+ struct mp_leg *g = &t->leg[t->n_leg];
+ copy(g->mode, sizeof g->mode, str(l, "mode"));
+ const char *line = str(l, "displayName");
+ copy(g->line, sizeof g->line,
+ line ? line : str(l, "routeShortName"));
+ copy(g->agency, sizeof g->agency, str(l, "agencyName"));
+ copy(g->headsign, sizeof g->headsign, str(l, "headsign"));
+ leg_place(g->from, sizeof g->from, janas_json_get(l, "from"));
+ leg_place(g->to, sizeof g->to, janas_json_get(l, "to"));
+ g->dep = mp_utc(str(l, "startTime"));
+ g->arr = mp_utc(str(l, "endTime"));
+ g->walk_m = janas_json_num(janas_json_get(l, "distance"), NAN);
+ const struct janas_json *rt = janas_json_get(l, "realTime");
+ g->real_time = rt && rt->type == JANAS_JSON_TRUE;
+ if (!tr->tz[0])
+ copy(tr->tz, sizeof tr->tz,
+ str(janas_json_get(l, "from"), "tz"));
+ if (g->mode[0])
+ t->n_leg++;
+ }
+ tr->n++;
+ }
+ int ok = its && its->type == JANAS_JSON_ARRAY;
+ janas_json_free(d);
+ if (!ok) {
+ snprintf(err, err_len, "Transitous: an answer without journeys");
+ return -1;
+ }
+ return 0;
+}
+
+/* ---- what is near ---- */
+
+static int by_distance(const void *a, const void *b)
+{
+ double x = ((const struct mp_poi *)a)->m, y = ((const struct mp_poi *)b)->m;
+ return (x > y) - (x < y);
+}
+
+int mp_read_overpass(const char *text, size_t n, double lat, double lon,
+ int max, struct mp_near *nr, char *err, size_t err_len)
+{
+ memset(nr, 0, sizeof *nr);
+ /* too busy, it answers a page of HTML, status 200 at times */
+ if (n && text[0] == '<') {
+ snprintf(err, err_len, "Overpass: %s",
+ strstr(text, "too busy") || strstr(text, "timeout")
+ ? "too busy now"
+ : "an error page instead of data");
+ return -1;
+ }
+ struct janas_json_doc *d = parse(text, n, "Overpass", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *els =
+ janas_json_get(janas_json_root(d), "elements");
+ if (!els || els->type != JANAS_JSON_ARRAY) {
+ const char *r = str(janas_json_root(d), "remark");
+ snprintf(err, err_len, "Overpass: %s", r ? r : "no elements");
+ janas_json_free(d);
+ return -1;
+ }
+ size_t cap = 64, have = 0;
+ struct mp_poi *all = malloc(cap * sizeof *all);
+ for (const struct janas_json *e = els->child; e && all; e = e->next) {
+ const struct janas_json *c = janas_json_get(e, "center");
+ double y = num(c ? c : e, "lat"), x = num(c ? c : e, "lon");
+ if (isnan(y) || isnan(x))
+ continue;
+ if (have == cap) {
+ struct mp_poi *g = realloc(all, 2 * cap * sizeof *all);
+ if (!g)
+ break;
+ all = g;
+ cap *= 2;
+ }
+ struct mp_poi *p = &all[have++];
+ memset(p, 0, sizeof *p);
+ const struct janas_json *t = janas_json_get(e, "tags");
+ const char *name = str(t, "name");
+ copy(p->name, sizeof p->name, name ? name : str(t, "brand"));
+ char road[128];
+ street(road, sizeof road, str(t, "addr:street"),
+ str(t, "addr:housenumber"));
+ const char *city = str(t, "addr:city");
+ if (road[0] && city)
+ snprintf(p->address, sizeof p->address, "%s, %s", road, city);
+ else
+ copy(p->address, sizeof p->address, road);
+ copy(p->hours, sizeof p->hours, str(t, "opening_hours"));
+ const char *ph = str(t, "phone");
+ copy(p->phone, sizeof p->phone, ph ? ph : str(t, "contact:phone"));
+ const char *type = str(e, "type");
+ double id = num(e, "id");
+ if (type && !isnan(id))
+ snprintf(p->osm, sizeof p->osm, "%s/%.0f", type, id);
+ p->lat = y;
+ p->lon = x;
+ p->m = geo_km(lat, lon, y, x) * 1000;
+ }
+ if (all)
+ qsort(all, have, sizeof *all, by_distance);
+ nr->found = (int)have;
+ for (size_t i = 0; all && i < have && nr->n < max && nr->n < MP_NEAR; i++)
+ nr->p[nr->n++] = all[i];
+ free(all);
+ janas_json_free(d);
+ return 0;
+}
diff --git a/src/maps/route.c b/src/maps/route.c
new file mode 100644
index 0000000..6dd802d
--- /dev/null
+++ b/src/maps/route.c
@@ -0,0 +1,159 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * route.c - maps_route (see maps.h): a route by car, bike or on foot from
+ * Valhalla, which gives the steps in the computer's language and a way or
+ * two besides; OSRM's, without the steps, when Valhalla does not answer.
+ * Both on the servers of FOSSGIS, for free and moderate use.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "maps.h"
+
+#define ROUTE_KEEP_S 600
+
+/* "car" as each engine names it */
+static const struct {
+ const char *mode, *valhalla, *osrm;
+} MODES[] = {{"car", "auto", "routed-car"},
+ {"bike", "bicycle", "routed-bike"},
+ {"foot", "pedestrian", "routed-foot"}};
+
+/* The computer's language when Valhalla writes its steps in it, else
+ English. */
+static const char *steps_lang(void)
+{
+ static const char *const known[] = {
+ "bg", "ca", "cs", "da", "de", "el", "en", "es", "et",
+ "fi", "fr", "hi", "hu", "it", "ja", "nb", "nl", "pl",
+ "pt", "ro", "ru", "sk", "sl", "sv", "tr", "uk"};
+ const char *l = mp_lang();
+ for (size_t i = 0; i < sizeof known / sizeof *known; i++)
+ if (strcmp(known[i], l) == 0)
+ return l;
+ return "en";
+}
+
+static int has(const struct janas_json *list, const char *what)
+{
+ for (const struct janas_json *v =
+ list && list->type == JANAS_JSON_ARRAY ? list->child : NULL;
+ v; v = v->next)
+ if (janas_json_is(v, what))
+ return 1;
+ return 0;
+}
+
+static int valhalla(const struct mp_place *pt[], int n, int m,
+ const struct janas_json *avoid, struct mp_routes *rs,
+ char *err, size_t err_len)
+{
+ struct janas_buf j = {0}, url = {0}, body = {0};
+ janas_buf_puts(&j, "{\"locations\": [");
+ for (int i = 0; i < n; i++)
+ janas_buf_printf(&j, "%s{\"lat\": %.6f, \"lon\": %.6f}", i ? ", " : "",
+ pt[i]->lat, pt[i]->lon);
+ janas_buf_printf(&j,
+ "], \"costing\": \"%s\", \"directions_options\": "
+ "{\"units\": \"kilometers\", \"language\": \"%s\"}",
+ MODES[m].valhalla, steps_lang());
+ if (n == 2) /* other ways, between two places only */
+ janas_buf_puts(&j, ", \"alternates\": 2");
+ if (has(avoid, "tolls") || has(avoid, "highways") ||
+ has(avoid, "ferries")) {
+ janas_buf_printf(&j, ", \"costing_options\": {\"%s\": {",
+ MODES[m].valhalla);
+ const char *sep = "";
+ if (has(avoid, "tolls")) {
+ janas_buf_printf(&j, "%s\"use_tolls\": 0", sep);
+ sep = ", ";
+ }
+ if (has(avoid, "highways")) {
+ janas_buf_printf(&j, "%s\"use_highways\": 0", sep);
+ sep = ", ";
+ }
+ if (has(avoid, "ferries"))
+ janas_buf_printf(&j, "%s\"use_ferry\": 0", sep);
+ janas_buf_puts(&j, "}}");
+ }
+ janas_buf_puts(&j, "}");
+ janas_buf_put(&j, "", 1);
+ janas_buf_printf(
+ &url, "%s/route?json=",
+ mp_base("JANAS_VALHALLA_URL", "https://valhalla1.openstreetmap.de"));
+ if (!j.oom)
+ mp_url_put(&url, j.p);
+ janas_buf_free(&j);
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, ROUTE_KEEP_S, &body, err, err_len);
+ janas_buf_free(&url);
+ int rc = -1;
+ /* an answer of 400 says why: no road near a place, too far */
+ if (status == 200 || status == 400)
+ rc = mp_read_valhalla(body.p ? body.p : "", body.n, rs, err, err_len);
+ else if (status > 0)
+ snprintf(err, err_len, "Valhalla: HTTP %d", status);
+ janas_buf_free(&body);
+ return rc;
+}
+
+static int osrm(const struct mp_place *pt[], int n, int m, struct mp_routes *rs,
+ char *err, size_t err_len)
+{
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(
+ &url, "%s/%s/route/v1/driving/",
+ mp_base("JANAS_OSRM_URL", "https://routing.openstreetmap.de"),
+ MODES[m].osrm);
+ for (int i = 0; i < n; i++)
+ janas_buf_printf(&url, "%s%.6f,%.6f", i ? ";" : "", pt[i]->lon,
+ pt[i]->lat);
+ janas_buf_puts(&url, "?overview=false&steps=true&alternatives=true");
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, ROUTE_KEEP_S, &body, err, err_len);
+ janas_buf_free(&url);
+ int rc = -1;
+ if (status == 200 || status == 400)
+ rc = mp_read_osrm(body.p ? body.p : "", body.n, rs, err, err_len);
+ else if (status > 0)
+ snprintf(err, err_len, "OSRM: HTTP %d", status);
+ janas_buf_free(&body);
+ return rc;
+}
+
+int mp_tool_route(const struct janas_json *args, struct janas_buf *b)
+{
+ const char *mode = mp_arg_str(args, "mode");
+ int m = 0;
+ for (size_t i = 0; mode && i < sizeof MODES / sizeof *MODES; i++)
+ if (strcmp(mode, MODES[i].mode) == 0)
+ m = (int)i;
+ struct mp_place from, via, to;
+ if (mp_arg_place(args, "from", 1, NAN, NAN, &from, b) != 0 ||
+ mp_arg_place(args, "to", 0, from.lat, from.lon, &to, b) != 0)
+ return 0;
+ int has_via = mp_arg_str(args, "via") != NULL;
+ if (has_via &&
+ mp_arg_place(args, "via", 0, from.lat, from.lon, &via, b) != 0)
+ return 0;
+ const struct mp_place *pt[3] = {&from, has_via ? &via : &to, &to};
+ int n = has_via ? 3 : 2;
+ struct mp_routes rs;
+ char e1[384] = "", e2[384] = "";
+ int ok = valhalla(pt, n, m, janas_json_get(args, "avoid"), &rs, e1,
+ sizeof e1) == 0;
+ if (!ok)
+ ok = osrm(pt, n, m, &rs, e2, sizeof e2) == 0;
+ if (!ok) {
+ struct janas_buf out = {0};
+ janas_buf_printf(&out, "No route from %s to %s: %s%s%s.", from.name,
+ to.name, e1, e2[0] ? "; " : "", e2);
+ return mp_result(&out, b, 1);
+ }
+ struct janas_buf d = {0};
+ mp_route_data(&d, &from, has_via ? &via : NULL, &to, MODES[m].mode, &rs);
+ mp_routes_free(&rs);
+ return mp_answer(b, "maps_route", &d, MP_ROUTE_LAYOUT, MP_ROUTE_BRIEF);
+}
diff --git a/src/maps/tools.c b/src/maps/tools.c
new file mode 100644
index 0000000..a00941d
--- /dev/null
+++ b/src/maps/tools.c
@@ -0,0 +1,185 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * tools.c - the tools janas-maps offers (see maps.h): maps_route,
+ * maps_transit, maps_nearby and maps_find, and what they share: their
+ * arguments, the places asked for, the answer as data with a layout. The
+ * tools themselves are in route.c, transit.c, nearby.c and place.c.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "common/locate.h"
+#include "common/mcp_server.h"
+#include "common/template.h"
+#include "maps.h"
+
+/* The model reads all of it before it can use a tool: every word costs. */
+#define PLACE_TEXT \
+ "A place or an address with its town (\\\"Via Roma 10, Trapani\\\", " \
+ "\\\"Colosseo\\\"), or \\\"lat,lon\\\"."
+
+void mp_tools_list(void *ctx, struct janas_buf *b)
+{
+ (void)ctx;
+ janas_buf_puts(
+ b, "\"tools\": [{\"name\": \"maps_route\", \"title\": \"A route by "
+ "road\", \"description\": \"The route between places by car, bike "
+ "or on foot: distance, time, roads, and the way step by step.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {\"from\": "
+ "{\"type\": \"string\", \"description\": \"" PLACE_TEXT
+ " Leave it out for where the user is (\\\"near me\\\"): "
+ "never a place only talked of.\"}, \"to\": {\"type\": "
+ "\"string\", \"description\": \"" PLACE_TEXT
+ "\"}, \"via\": {\"type\": \"string\", \"description\": \"A place "
+ "to pass through.\"}, \"mode\": {\"type\": \"string\", \"enum\": "
+ "[\"car\", \"bike\", \"foot\"]}, \"avoid\": {\"type\": \"array\", "
+ "\"items\": {\"type\": \"string\", \"enum\": [\"tolls\", "
+ "\"highways\", \"ferries\"]}}}, \"required\": [\"to\"], "
+ "\"additionalProperties\": false}}, "
+ "{\"name\": \"maps_transit\", \"title\": \"Public transport\", "
+ "\"description\": \"Journeys by train, bus, metro or ferry between "
+ "places, from the timetables.\", \"inputSchema\": {\"type\": "
+ "\"object\", \"properties\": {\"from\": {\"type\": \"string\", "
+ "\"description\": \"" PLACE_TEXT
+ " Leave it out for where the user is (\\\"near me\\\"): "
+ "never a place only talked of.\"}, \"to\": {\"type\": "
+ "\"string\", \"description\": \"" PLACE_TEXT
+ "\"}, \"when\": {\"type\": \"string\", \"description\": \"Local "
+ "time, HH:MM or YYYY-MM-DD HH:MM (default now).\"}, \"arrive_by\": "
+ "{\"type\": \"boolean\", \"description\": \"The time is to arrive "
+ "by, not to leave at.\"}}, \"required\": [\"to\"], "
+ "\"additionalProperties\": false}}, "
+ "{\"name\": \"maps_nearby\", \"title\": \"What is near\", "
+ "\"description\": \"Places of a kind near a place, nearest first: "
+ "fuel, pharmacies, cash machines, stations...\", \"inputSchema\": "
+ "{\"type\": \"object\", \"properties\": {\"what\": {\"type\": "
+ "\"string\", \"enum\": [");
+ for (size_t i = 0; i < MP_N_KINDS; i++)
+ janas_buf_printf(b, "%s\"%s\"", i ? ", " : "", MP_KINDS[i].name);
+ janas_buf_puts(
+ b, "]}, \"place\": {\"type\": \"string\", \"description\": "
+ "\"" PLACE_TEXT
+ " Leave it out for where the user is (\\\"near me\\\"): "
+ "never a place only talked of.\"}, "
+ "\"radius\": {\"type\": \"number\", \"minimum\": 0.1, "
+ "\"maximum\": 10, \"description\": \"km (default 2).\"}}, "
+ "\"required\": [\"what\"], \"additionalProperties\": false}}, "
+ "{\"name\": \"maps_find\", \"title\": \"Where a place is\", "
+ "\"description\": \"A place's or an address' full address, "
+ "coordinates and map link.\", \"inputSchema\": {\"type\": "
+ "\"object\", \"properties\": {\"place\": {\"type\": \"string\", "
+ "\"description\": \"" PLACE_TEXT "\"}}, \"required\": "
+ "[\"place\"], \"additionalProperties\": false}}]");
+}
+
+int mp_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b)
+{
+ (void)ctx;
+ const struct janas_json *name = janas_json_get(params, "name");
+ const struct janas_json *args = janas_json_get(params, "arguments");
+ if (args && args->type != JANAS_JSON_OBJECT)
+ args = NULL;
+ if (janas_json_is(name, "maps_route"))
+ return mp_tool_route(args, b);
+ if (janas_json_is(name, "maps_transit"))
+ return mp_tool_transit(args, b);
+ if (janas_json_is(name, "maps_nearby"))
+ return mp_tool_nearby(args, b);
+ if (janas_json_is(name, "maps_find"))
+ return mp_tool_find(args, b);
+ return -1;
+}
+
+/* ---- what the tools share ---- */
+
+const char *mp_arg_str(const struct janas_json *args, const char *name)
+{
+ const char *s = janas_json_str(janas_json_get(args, name));
+ return s && *s ? s : NULL;
+}
+
+double mp_arg_num(const struct janas_json *args, const char *name, double def)
+{
+ const struct janas_json *v = janas_json_get(args, name);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, def) : def;
+}
+
+int mp_arg_bool(const struct janas_json *args, const char *name, int def)
+{
+ const struct janas_json *v = janas_json_get(args, name);
+ if (v && v->type == JANAS_JSON_TRUE)
+ return 1;
+ if (v && v->type == JANAS_JSON_FALSE)
+ return 0;
+ return def;
+}
+
+int mp_result(struct janas_buf *out, struct janas_buf *b, int is_error)
+{
+ janas_mcps_text_result(b, out->p ? out->p : "", out->n, is_error);
+ janas_buf_free(out);
+ return 0;
+}
+
+int mp_arg_place(const struct janas_json *args, const char *name, int here,
+ double near_lat, double near_lon, struct mp_place *p,
+ struct janas_buf *b)
+{
+ const char *q = mp_arg_str(args, name);
+ char err[512];
+ if (q && mp_place_find(q, near_lat, near_lon, p, err, sizeof err) == 0)
+ return 0;
+ struct janas_where w;
+ if (!q && here && janas_where(&w, err, sizeof err) == 0) {
+ mp_place_at(w.lat, w.lon, p);
+ /* "3 km WNW of Palermo" says more than a guess knows: its town */
+ if (w.city[0])
+ snprintf(p->name, sizeof p->name, "%s", w.city);
+ snprintf(p->how, sizeof p->how, "%s", w.how);
+ p->address[0] = 0; /* its coordinates: a guess's, not an address */
+ return 0;
+ }
+ struct janas_buf out = {0};
+ if (!q && here)
+ janas_buf_printf(&out, "No %s given, and %s.", name, err);
+ else if (!q)
+ janas_buf_printf(&out, "No %s given.", name);
+ else
+ janas_buf_printf(&out,
+ "%s. Ask the user which place, or give it with its "
+ "town (\"Via Roma 10, Trapani\").",
+ err);
+ mp_result(&out, b, 1);
+ return -1;
+}
+
+int mp_answer(struct janas_buf *b, const char *name, struct janas_buf *d,
+ const char *layout, const char *brief)
+{
+ char err[300];
+ if (d->oom || janas_tpl_result(b, name, d->p, d->n, layout, brief, err,
+ sizeof err) != 0) {
+ struct janas_buf out = {0};
+ janas_buf_printf(&out, "The answer could not be written: %s.",
+ d->oom ? "out of memory" : err);
+ janas_buf_free(d);
+ return mp_result(&out, b, 1);
+ }
+ janas_buf_free(d);
+ return 0;
+}
+
+int mp_tool_find(const struct janas_json *args, struct janas_buf *b)
+{
+ struct mp_place p;
+ if (mp_arg_place(args, "place", 0, NAN, NAN, &p, b) != 0)
+ return 0;
+ if (!p.address[0]) /* a point: what is there */
+ mp_place_reverse(p.lat, p.lon, &p);
+ struct janas_buf d = {0};
+ mp_find_data(&d, &p);
+ return mp_answer(b, "maps_find", &d, MP_FIND_LAYOUT, MP_FIND_BRIEF);
+}
diff --git a/src/maps/transit.c b/src/maps/transit.c
new file mode 100644
index 0000000..3a6984f
--- /dev/null
+++ b/src/maps/transit.c
@@ -0,0 +1,129 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * transit.c - maps_transit (see maps.h): journeys by public transport from
+ * Transitous, a community's router (MOTIS) over the operators' open
+ * timetables, free for open-source, non-commercial and light use. Times
+ * are asked and told in the start's zone.
+ */
+#define _GNU_SOURCE /* timegm */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/geo.h"
+#include "maps.h"
+
+#define TRANSIT_KEEP_S 120
+
+/* The zone of a point, from the tables: its city's, else its airport's. */
+static const char *zone_of(double lat, double lon)
+{
+ double km;
+ const struct geo_city *c = geo_city_near(lat, lon, &km);
+ if (c)
+ return geo_tz_name(c->tz);
+ const struct geo_airport *a = geo_airport_near(lat, lon, &km);
+ return a ? geo_tz_name(a->tz) : NULL;
+}
+
+/* "08:30", "2026-10-03 08:30" or "2026-10-03T08:30", local to tz: the
+ time, or -1. A time of the day already gone is tomorrow's. */
+static time_t local_time(const char *s, const char *tz)
+{
+ struct tm tm = {0};
+ int y, mo, d, h, mi, whole = 0;
+ if (sscanf(s, "%d-%d-%d%*[ T]%d:%d", &y, &mo, &d, &h, &mi) == 5)
+ whole = 1;
+ else if (sscanf(s, "%d:%d", &h, &mi) != 2)
+ return -1;
+ if (h < 0 || h > 23 || mi < 0 || mi > 59)
+ return -1;
+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;
+ if (tz && *tz)
+ setenv("TZ", tz, 1);
+ tzset();
+ time_t now = time(NULL);
+ localtime_r(&now, &tm);
+ if (whole) {
+ tm.tm_year = y - 1900;
+ tm.tm_mon = mo - 1;
+ tm.tm_mday = d;
+ }
+ tm.tm_hour = h;
+ tm.tm_min = mi;
+ tm.tm_sec = 0;
+ tm.tm_isdst = -1;
+ time_t t = mktime(&tm);
+ if (!whole && t != -1 && t < now - 600) {
+ tm.tm_mday++;
+ tm.tm_isdst = -1;
+ t = mktime(&tm);
+ }
+ if (tz && *tz) {
+ if (old)
+ setenv("TZ", old, 1);
+ else
+ unsetenv("TZ");
+ tzset();
+ }
+ free(old);
+ return t;
+}
+
+int mp_tool_transit(const struct janas_json *args, struct janas_buf *b)
+{
+ struct mp_place from, to;
+ if (mp_arg_place(args, "from", 1, NAN, NAN, &from, b) != 0 ||
+ mp_arg_place(args, "to", 0, from.lat, from.lon, &to, b) != 0)
+ return 0;
+ const char *tz = zone_of(from.lat, from.lon);
+ const char *when = mp_arg_str(args, "when");
+ time_t t = when ? local_time(when, tz) : -1;
+ if (when && t == -1) {
+ struct janas_buf out = {0};
+ janas_buf_printf(&out,
+ "\"%s\" is not a time: give HH:MM, or YYYY-MM-DD "
+ "HH:MM.",
+ when);
+ return mp_result(&out, b, 1);
+ }
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_printf(
+ &url, "%s/api/v1/plan?fromPlace=%.6f,%.6f&toPlace=%.6f,%.6f",
+ mp_base("JANAS_TRANSITOUS_URL", "https://api.transitous.org"), from.lat,
+ from.lon, to.lat, to.lon);
+ if (t != -1) {
+ struct tm g;
+ gmtime_r(&t, &g);
+ janas_buf_printf(&url, "&time=%04d-%02d-%02dT%02d:%02d:00Z",
+ g.tm_year + 1900, g.tm_mon + 1, g.tm_mday, g.tm_hour,
+ g.tm_min);
+ }
+ if (mp_arg_bool(args, "arrive_by", 0))
+ janas_buf_puts(&url, "&arriveBy=true");
+ char err[384] = "";
+ int status =
+ url.oom ? -1 : mp_fetch(url.p, TRANSIT_KEEP_S, &body, err, sizeof err);
+ janas_buf_free(&url);
+ struct mp_transit tr;
+ int ok = status == 200 &&
+ mp_read_transit(body.p, body.n, &tr, err, sizeof err) == 0;
+ if (status > 0 && status != 200)
+ snprintf(err, sizeof err, "Transitous: HTTP %d", status);
+ janas_buf_free(&body);
+ if (!ok) {
+ struct janas_buf out = {0};
+ janas_buf_printf(&out, "No journeys from %s to %s: %s.", from.name,
+ to.name, err);
+ return mp_result(&out, b, 1);
+ }
+ if (!tr.tz[0] && tz)
+ snprintf(tr.tz, sizeof tr.tz, "%s", tz);
+ struct janas_buf d = {0};
+ mp_transit_data(&d, &from, &to, &tr);
+ return mp_answer(b, "maps_transit", &d, MP_TRANSIT_LAYOUT,
+ MP_TRANSIT_BRIEF);
+}
diff --git a/tests/test_layout.c b/tests/test_layout.c
index 97415fd..c5a04fd 100644
--- a/tests/test_layout.c
+++ b/tests/test_layout.c
@@ -104,6 +104,26 @@ int main(void)
free(again);
free(it);
+ /* lines added by the model between two tags are not kept: those
+ between tags alone come from English */
+ {
+ static const char LEGS[] = "Trips:\n{{#legs}}\n- {{to}}\n{{/legs}}\n"
+ "{{#cut}} and {{cut}} more{{/cut}}\n";
+ struct coded c;
+ CHECK(encode(LEGS, &c) == 0, "encode");
+ char why[200] = "";
+ char *d = decode(&c,
+ "Viaggi:\n{1}\n\n- {2}\n{3}\n\n\n{4} e altri {5} "
+ "{6}\n=== words\n",
+ why, sizeof why);
+ CHECK(d && strcmp(d, "Viaggi:\n{{#legs}}\n- {{to}}\n{{/legs}}\n"
+ "{{#cut}} e altri {{cut}} {{/cut}}\n---\n"
+ "decimal = ,\n") == 0,
+ "the lines between tags:\n%s%s", d ? d : "NULL ", why);
+ free(d);
+ coded_free(&c);
+ }
+
/* tidy up: the one file and the two directories made here */
char path[1200];
snprintf(path, sizeof path, "%s/janas/layouts/test.it.%016llx.txt", dir,
diff --git a/tests/test_maps_parse.c b/tests/test_maps_parse.c
new file mode 100644
index 0000000..1f28751
--- /dev/null
+++ b/tests/test_maps_parse.c
@@ -0,0 +1,439 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_maps_parse.c - janas-maps' reading of its sources' answers, without
+ * the network, and the layouts filled with what was read: Valhalla's route
+ * from Trapani to Palermo and another way (cut to a few steps), an error
+ * of it, OSRM's route, Transitous' journey, Overpass' pharmacies (and a
+ * way without a name), Nominatim's and Photon's places, as they came on 2
+ * October 2026.
+ * The sources belong to the program, so they are compiled in here.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "common/template.h"
+#include "maps/data.c"
+#include "maps/layouts.c"
+#include "maps/nearby.c"
+#include "maps/read.c"
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+/* nearby.c's tool, and what the tools need, are not tested here */
+int mp_arg_place(const struct janas_json *args, const char *name, int here,
+ double near_lat, double near_lon, struct mp_place *p,
+ struct janas_buf *b)
+{
+ (void)args, (void)name, (void)here, (void)near_lat, (void)near_lon;
+ (void)p, (void)b;
+ return -1;
+}
+double mp_arg_num(const struct janas_json *args, const char *name, double def)
+{
+ (void)args, (void)name;
+ return def;
+}
+const char *mp_arg_str(const struct janas_json *args, const char *name)
+{
+ (void)args, (void)name;
+ return NULL;
+}
+int mp_result(struct janas_buf *out, struct janas_buf *b, int is_error)
+{
+ (void)b, (void)is_error;
+ janas_buf_free(out);
+ return 0;
+}
+int mp_answer(struct janas_buf *b, const char *name, struct janas_buf *d,
+ const char *layout, const char *brief)
+{
+ (void)b, (void)name, (void)layout, (void)brief;
+ janas_buf_free(d);
+ return 0;
+}
+int mp_fetch(const char *url, int keep_s, struct janas_buf *out, char *err,
+ size_t err_len)
+{
+ (void)url, (void)keep_s, (void)out, (void)err, (void)err_len;
+ return -1;
+}
+const char *mp_base(const char *env, const char *def)
+{
+ (void)env;
+ return def;
+}
+void mp_url_put(struct janas_buf *b, const char *s)
+{
+ janas_buf_puts(b, s);
+}
+
+static const char VALHALLA[] =
+ "{\"trip\": {\"language\": \"it\", \"summary\": {\"has_toll\": true, \"has_hig"
+ "hway\": true, \"has_ferry\": false, \"time\": 5950.149, \"length\": 110.4"
+ "9}, \"legs\": [{\"maneuvers\": [{\"type\": 3, \"instruction\": \"Guida vers"
+ "o est su Via Giardini.\", \"length\": 0.028, \"street_names\": [\"Via Gi"
+ "ardini\"]}, {\"type\": 10, \"instruction\": \"Svolta a destra su Via Pal"
+ "merio Abate.\", \"length\": 0.048, \"street_names\": [\"Via Palmerio Aba"
+ "te\"]}, {\"type\": 27, \"instruction\": \"Esci dalla rotonda verso A29di"
+ "r/Palermo.\", \"length\": 7.424, \"street_names\": [\"A29dir\", \"E 933\"]}"
+ ", {\"type\": 24, \"instruction\": \"Mantieni la sinistra per rimanere s"
+ "u E 933 verso Palermo.\", \"length\": 29.193, \"street_names\": [\"E 933"
+ "\"]}, {\"type\": 20, \"instruction\": \"Prendi l'uscita A29 verso Palerm"
+ "o/aeroporto Falcone Borsellino.\", \"length\": 58.84, \"street_names\":"
+ " [\"E 90\"]}, {\"type\": 4, \"instruction\": \"Sei arrivato a destinazion"
+ "e.\", \"length\": 0.0}]}]}, \"alternates\": [{\"trip\": {\"summary\": {\"has"
+ "_toll\": false, \"has_highway\": true, \"has_ferry\": false, \"time\": 71"
+ "57.349, \"length\": 104.988}, \"legs\": [{\"maneuvers\": [{\"type\": 24, \""
+ "instruction\": \"Mantieni la sinistra per rimanere su E 933 verso Pa"
+ "lermo.\", \"length\": 29.193, \"street_names\": [\"E 933\"]}, {\"type\": 20"
+ ", \"instruction\": \"Prendi l'uscita A29 verso Palermo/aeroporto Falc"
+ "one Borsellino.\", \"length\": 21.372, \"street_names\": [\"A29\", \"E 90\""
+ ", \"Autostrada Palermo-Mazara del Vallo\"]}, {\"type\": 20, \"instructi"
+ "on\": \"Prendi l'uscita.\", \"length\": 17.315, \"street_names\": [\"SS624"
+ "\"]}]}]}}]}";
+
+static const char VALHALLA_ERROR[] =
+ "{\"error_code\": 442, \"error\": \"No path could be found for input\", \""
+ "status_code\": 400, \"status\": \"Bad Request\"}";
+
+static const char OSRM[] =
+ "{\"code\": \"Ok\", \"routes\": [{\"distance\": 109363, \"duration\": 5731.7,"
+ " \"legs\": [{\"summary\": \"Autostrada Alcamo-Trapani, Autostrada Paler"
+ "mo-Mazara del Vallo\"}]}]}";
+
+static const char TRANSIT[] =
+ "{\"itineraries\": [{\"duration\": 13200, \"startTime\": \"2026-10-02T03:4"
+ "2:00Z\", \"endTime\": \"2026-10-02T07:22:00Z\", \"transfers\": 2, \"legs\":"
+ " [{\"mode\": \"WALK\", \"startTime\": \"2026-10-02T03:42:00Z\", \"endTime\":"
+ " \"2026-10-02T03:50:00Z\", \"from\": {\"name\": \"START\", \"tz\": \"Europe/R"
+ "ome\"}, \"to\": {\"name\": \"TRAPANI\"}, \"distance\": 494.0, \"realTime\": f"
+ "alse}, {\"mode\": \"REGIONAL_RAIL\", \"startTime\": \"2026-10-02T03:50:00"
+ "Z\", \"endTime\": \"2026-10-02T04:26:00Z\", \"from\": {\"name\": \"TRAPANI\","
+ " \"tz\": \"Europe/Rome\"}, \"to\": {\"name\": \"MARSALA\"}, \"displayName\": \""
+ "REG 21854\", \"routeShortName\": \"REG 21854\", \"agencyName\": \"TRENITAL"
+ "IA\", \"headsign\": \"\", \"realTime\": false}, {\"mode\": \"WALK\", \"startTi"
+ "me\": \"2026-10-02T04:26:00Z\", \"endTime\": \"2026-10-02T04:28:00Z\", \"f"
+ "rom\": {\"name\": \"MARSALA\", \"tz\": \"Europe/Rome\"}, \"to\": {\"name\": \"MA"
+ "RSALA-VIA AMERIGO FAZIO\"}, \"distance\": 418.0, \"realTime\": false}, "
+ "{\"mode\": \"BUS\", \"startTime\": \"2026-10-02T04:30:00Z\", \"endTime\": \"2"
+ "026-10-02T07:05:00Z\", \"from\": {\"name\": \"MARSALA-VIA AMERIGO FAZIO\""
+ ", \"tz\": \"Europe/Rome\"}, \"to\": {\"name\": \"PALERMO (Piazza Cairoli)\"}"
+ ", \"displayName\": \"MARSALA-VIA AMERIGO FAZIO - PALERMO P.zza Cairol"
+ "i\", \"routeShortName\": \"MARSALA-VIA AMERIGO FAZIO - PALERMO P.zza C"
+ "airoli\", \"agencyName\": \"Salemi\", \"headsign\": \"Palermo P.Zza Cairol"
+ "i\", \"realTime\": false}, {\"mode\": \"WALK\", \"startTime\": \"2026-10-02T"
+ "07:05:00Z\", \"endTime\": \"2026-10-02T07:09:00Z\", \"from\": {\"name\": \"P"
+ "ALERMO (Piazza Cairoli)\", \"tz\": \"Europe/Rome\"}, \"to\": {\"name\": \"ST"
+ "AZIONE CENTRALE GIULIO CESARE\"}, \"distance\": 485.0, \"realTime\": fa"
+ "lse}, {\"mode\": \"BUS\", \"startTime\": \"2026-10-02T07:12:00Z\", \"endTim"
+ "e\": \"2026-10-02T07:17:00Z\", \"from\": {\"name\": \"STAZIONE CENTRALE GI"
+ "ULIO CESARE\", \"tz\": \"Europe/Rome\"}, \"to\": {\"name\": \"ROMA LATTARINI"
+ "\"}, \"displayName\": \"101\", \"routeShortName\": \"101\", \"agencyName\": \""
+ "AMAT Palermo S.p.A.\", \"headsign\": \"STADIO\", \"realTime\": false}, {\""
+ "mode\": \"WALK\", \"startTime\": \"2026-10-02T07:17:00Z\", \"endTime\": \"20"
+ "26-10-02T07:22:00Z\", \"from\": {\"name\": \"ROMA LATTARINI\", \"tz\": \"Eur"
+ "ope/Rome\"}, \"to\": {\"name\": \"END\"}, \"distance\": 300.0, \"realTime\": "
+ "false}]}]}";
+
+static const char OVERPASS[] =
+ "{\"version\": 0.6, \"elements\": [{\"type\": \"node\", \"id\": 1073287420, \""
+ "lat\": 38.0152454, \"lon\": 12.5137922, \"tags\": {\"amenity\": \"pharmacy"
+ "\", \"dispensing\": \"yes\", \"healthcare\": \"pharmacy\", \"name\": \"Occhipi"
+ "nti\", \"operator\": \"Vito Occhipinti\", \"phone\": \"+39092321663\", \"ref"
+ ":msal\": \"15725\", \"ref:vatin\": \"IT01922580814\", \"source\": \"DatiOpen"
+ ".it - Provincia Regionale di Trapani\", \"source:url\": \"http://www.d"
+ "atiopen.it/it/data/Farmacie_della_Provincia_di_Trapani\"}}, {\"type\""
+ ": \"node\", \"id\": 1073287769, \"lat\": 38.0158833, \"lon\": 12.5107126, "
+ "\"tags\": {\"addr:housenumber\": \"37\", \"addr:postcode\": \"91100\", \"addr"
+ ":street\": \"Via della Cuba\", \"amenity\": \"pharmacy\", \"dispensing\": \""
+ "yes\", \"healthcare\": \"pharmacy\", \"name\": \"Giglio Ruggiero & C. s.n."
+ "c.\", \"ref:msal\": \"15690\", \"ref:vatin\": \"IT02166410817\", \"source\": "
+ "\"DatiOpen.it - Provincia Regionale di Trapani\", \"source:url\": \"htt"
+ "p://www.datiopen.it/it/data/Farmacie_della_Provincia_di_Trapani\"}}"
+ ", {\"type\": \"node\", \"id\": 1073453284, \"lat\": 38.0150992, \"lon\": 12."
+ "5075134, \"tags\": {\"addr:housenumber\": \"32\", \"addr:postcode\": \"9110"
+ "0\", \"addr:street\": \"Via San Francesco d'Assisi\", \"amenity\": \"pharm"
+ "acy\", \"dispensing\": \"yes\", \"healthcare\": \"pharmacy\", \"name\": \"Rest"
+ "ivo Ilaria\", \"ref:msal\": \"15695\", \"ref:vatin\": \"IT00094860814\", \"s"
+ "ource\": \"DatiOpen.it - Provincia Regionale di Trapani\", \"source:ur"
+ "l\": \"http://www.datiopen.it/it/data/Farmacie_della_Provincia_di_Tr"
+ "apani\"}}, {\"type\": \"node\", \"id\": 1624173475, \"lat\": 38.0193717, \"l"
+ "on\": 12.5215576, \"tags\": {\"addr:housenumber\": \"119\", \"addr:street\""
+ ": \"Via Giovanbattista Fardella\", \"amenity\": \"pharmacy\", \"dispensin"
+ "g\": \"yes\", \"healthcare\": \"pharmacy\", \"name\": \"Garraffa Vincenzo\", "
+ "\"ref:msal\": \"15710\", \"ref:vatin\": \"IT02373400817\", \"source\": \"Dati"
+ "Open.it - Provincia Regionale di Trapani\", \"source:url\": \"http://w"
+ "ww.datiopen.it/it/data/Farmacie_della_Provincia_di_Trapani\"}}, {\"t"
+ "ype\": \"way\", \"id\": 4242, \"center\": {\"lat\": 38.0176, \"lon\": 12.5151"
+ "}, \"tags\": {\"amenity\": \"pharmacy\", \"opening_hours\": \"Mo-Sa 08:30-1"
+ "3:00,16:30-20:00\"}}]}";
+
+static const char NOMINATIM[] =
+ "[{\"place_id\": 53253714, \"licence\": \"Data © OpenStreetMap contribut"
+ "ors, ODbL 1.0. http://osm.org/copyright\", \"osm_type\": \"way\", \"osm_"
+ "id\": 381762269, \"lat\": \"38.1101703\", \"lon\": \"13.3680470\", \"categor"
+ "y\": \"railway\", \"type\": \"platform\", \"place_rank\": 30, \"importance\":"
+ " 7.561226825355943e-05, \"addresstype\": \"railway\", \"name\": \"Stazion"
+ "e Centrale\", \"display_name\": \"Stazione Centrale, Via Paolo Balsamo"
+ ", Brancaccio, II Circoscrizione, Palermo, Sicilia, 90123, Italia\","
+ " \"address\": {\"railway\": \"Stazione Centrale\", \"road\": \"Via Paolo Ba"
+ "lsamo\", \"suburb\": \"Brancaccio\", \"city\": \"Palermo\", \"county\": \"Pale"
+ "rmo\", \"ISO3166-2-lvl6\": \"IT-PA\", \"state\": \"Sicilia\", \"ISO3166-2-lv"
+ "l4\": \"IT-82\", \"postcode\": \"90123\", \"country\": \"Italia\", \"country_c"
+ "ode\": \"it\"}, \"boundingbox\": [\"38.1100702\", \"38.1102703\", \"13.36783"
+ "15\", \"13.3682624\"]}]";
+
+static const char PHOTON[] =
+ "{\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\", \"pr"
+ "operties\": {\"osm_type\": \"W\", \"osm_id\": 105508402, \"osm_key\": \"high"
+ "way\", \"osm_value\": \"residential\", \"type\": \"street\", \"name\": \"Via M"
+ "ichelangelo Fardella\", \"district\": \"Trapani\", \"city\": \"Trapani\", \""
+ "county\": \"Trapani\", \"state\": \"Sicilia\", \"country\": \"Italia\", \"post"
+ "code\": \"91100\", \"countrycode\": \"IT\", \"extent\": [12.5251702, 38.017"
+ "7973, 12.5256313, 38.0154919]}, \"geometry\": {\"type\": \"Point\", \"coo"
+ "rdinates\": [12.5253913, 38.0166427]}}]}";
+
+/* Nominatim's "Trapani", cut: the municipality, the province, the town */
+static const char TOWN[] =
+ "[{\"osm_type\": \"relation\", \"osm_id\": 39150, \"lat\": "
+ "\"37.9003731\", \"lon\": \"12.7116255\", \"category\": \"boundary\", "
+ "\"type\": \"administrative\", \"name\": \"Trapani\", \"display_name\": "
+ "\"Trapani, Sicilia, 91100, Italia\"}, {\"osm_type\": \"relation\", "
+ "\"osm_id\": 39151, \"lat\": \"37.8745486\", \"lon\": \"12.7179792\", "
+ "\"category\": \"boundary\", \"type\": \"administrative\", \"name\": "
+ "\"Trapani\"}, {\"osm_type\": \"node\", \"osm_id\": 1, \"lat\": "
+ "\"38.0173961\", \"lon\": \"12.5160225\", \"category\": \"place\", "
+ "\"type\": \"city\", \"name\": \"Trapani\"}]";
+
+/* The layout filled with the data: the text, or "" when it failed. */
+static char text[16384];
+
+static const char *fill(const char *layout, const struct janas_buf *d)
+{
+ text[0] = 0;
+ struct janas_json_doc *doc =
+ janas_json_parse(d->p ? d->p : "", d->n, NULL, 0);
+ CHECK(doc != NULL, "the data is not JSON:\n%.*s", (int)d->n, d->p);
+ if (!doc)
+ return text;
+ struct janas_buf out = {0};
+ char err[200];
+ if (janas_tpl_render(layout, strlen(layout), janas_json_root(doc), &out,
+ err, sizeof err) == 0)
+ snprintf(text, sizeof text, "%.*s", (int)out.n, out.p);
+ else
+ CHECK(0, "a layout not filled: %s", err);
+ janas_buf_free(&out);
+ janas_json_free(doc);
+ return text;
+}
+
+static void place(struct mp_place *p, const char *name, double lat, double lon)
+{
+ memset(p, 0, sizeof *p);
+ snprintf(p->name, sizeof p->name, "%s", name);
+ p->lat = lat;
+ p->lon = lon;
+}
+
+static void routes(void)
+{
+ struct mp_routes rs;
+ char err[256];
+ CHECK(mp_read_valhalla(VALHALLA, strlen(VALHALLA), &rs, err, sizeof err) ==
+ 0,
+ "Valhalla: %s", err);
+ CHECK(rs.n == 2 && fabs(rs.r[0].km - 110.49) < 0.01 &&
+ fabs(rs.r[0].min - 99.17) < 0.01 && rs.r[0].toll &&
+ rs.r[0].highway && !rs.r[1].toll,
+ "Valhalla: %d routes, %.2f km, %.2f min", rs.n, rs.r[0].km,
+ rs.r[0].min);
+ CHECK(strcmp(rs.r[0].roads, "A29dir, E 933, E 90") == 0,
+ "the roads: \"%s\"", rs.r[0].roads);
+ CHECK(rs.r[0].n_step == 6 && rs.r[1].step == NULL &&
+ strcmp(rs.r[0].step[5].text, "Sei arrivato a destinazione.") == 0,
+ "the steps: %d", rs.r[0].n_step);
+
+ struct mp_place from, to;
+ place(&from, "Trapani", 38.0175, 12.515);
+ snprintf(from.how, sizeof from.how,
+ "estimated from the internet connection (GeoJS)");
+ place(&to, "Palermo", 38.1157, 13.3615);
+ struct janas_buf d = {0};
+ mp_route_data(&d, &from, NULL, &to, "car", &rs);
+ mp_routes_free(&rs);
+ const char *t = fill(MP_ROUTE_LAYOUT, &d);
+ CHECK(strstr(t, "From Trapani (where the user is, estimated from the "
+ "internet connection (GeoJS)) to Palermo by car: 110 km, "
+ "about 1 h 39 min without traffic, by A29dir, E 933, E "
+ "90; with tolls.\n") == t,
+ "the route:\n%s", t);
+ CHECK(
+ strstr(t,
+ "Another way: 105 km, about 1 h 59 min, by E 933, A29, SS624."),
+ "the other way, without tolls:\n%s", t);
+ CHECK(strstr(t, "\n1. Guida verso est su Via Giardini. (30 m)\n") &&
+ strstr(t, "\n5. Prendi l'uscita A29 verso Palermo/aeroporto "
+ "Falcone Borsellino. (59 km)\n") &&
+ strstr(t, "\n6. Sei arrivato a destinazione.\n"),
+ "the steps, each with its own length:\n%s", t);
+ CHECK(strstr(t, "directions?engine=fossgis_valhalla_car&route=38.01750%"
+ "2C12.51500%3B38.11570%2C13.36150\n"),
+ "the link:\n%s", t);
+ t = fill(MP_ROUTE_BRIEF, &d);
+ CHECK(strstr(t, "car from Trapani (where the user is") == t &&
+ !strstr(t, "Guida"),
+ "the brief:\n%s", t);
+ janas_buf_free(&d);
+
+ CHECK(mp_read_valhalla(VALHALLA_ERROR, strlen(VALHALLA_ERROR), &rs, err,
+ sizeof err) == -1 &&
+ strstr(err, "No path could be found"),
+ "Valhalla's error: %s", err);
+ CHECK(mp_read_osrm(OSRM, strlen(OSRM), &rs, err, sizeof err) == 0 &&
+ rs.n == 1 && fabs(rs.r[0].km - 109.363) < 0.001 &&
+ strcmp(rs.r[0].roads, "Autostrada Alcamo-Trapani, Autostrada "
+ "Palermo-Mazara del Vallo") == 0 &&
+ rs.r[0].step == NULL,
+ "OSRM: %s", err);
+ mp_routes_free(&rs);
+ static const char far[] =
+ "{\"code\": \"Ok\", \"routes\": [{\"distance\": 3556000, "
+ "\"duration\": 139380, \"legs\": [{\"summary\": \"\"}]}], "
+ "\"waypoints\": [{\"distance\": 6.0}, {\"distance\": 2915000.5}]}";
+ CHECK(mp_read_osrm(far, strlen(far), &rs, err, sizeof err) == -1 &&
+ strstr(err, "2915 km from the nearest road"),
+ "OSRM, a place off its map: %s", err);
+}
+
+static void transit(void)
+{
+ CHECK(mp_utc("2026-10-02T03:42:00Z") == 1790912520 && mp_utc("x") == -1,
+ "mp_utc");
+ struct mp_transit tr;
+ char err[256];
+ CHECK(mp_read_transit(TRANSIT, strlen(TRANSIT), &tr, err, sizeof err) ==
+ 0 &&
+ tr.n == 1 && tr.t[0].n_leg == 7 && tr.t[0].transfers == 2 &&
+ strcmp(tr.tz, "Europe/Rome") == 0,
+ "Transitous: %s", err);
+ struct mp_place from, to;
+ place(&from, "Via Giardini, Trapani", 38.0175, 12.515);
+ place(&to, "Palermo", 38.1157, 13.3615);
+ struct janas_buf d = {0};
+ mp_transit_data(&d, &from, &to, &tr);
+ const char *t = fill(MP_TRANSIT_LAYOUT, &d);
+ CHECK(strstr(t, "By public transport from Via Giardini, Trapani to "
+ "Palermo; journeys found: 1.\n") == t &&
+ strstr(t, "\n1. Leaves at 05:42") &&
+ strstr(t, "(3 h 40 min, changes: 2):\n") &&
+ strstr(t, " - walk 8 min, 490 m to TRAPANI\n") &&
+ strstr(t, " - 05:50 regional train REG 21854 (TRENITALIA) "
+ "from TRAPANI; 06:26 get off at MARSALA\n") &&
+ strstr(t, " to Palermo\n") && strstr(t, "local (Europe/Rome)"),
+ "the journeys:\n%s", t);
+ janas_buf_free(&d);
+}
+
+static void near(void)
+{
+ struct mp_near nr;
+ char err[256];
+ CHECK(mp_read_overpass(OVERPASS, strlen(OVERPASS), 38.0175, 12.515, 10, &nr,
+ err, sizeof err) == 0 &&
+ nr.found == 5 && nr.n == 5,
+ "Overpass: %s", err);
+ for (int i = 1; i < nr.n; i++)
+ CHECK(nr.p[i].m >= nr.p[i - 1].m, "not the nearest first");
+ CHECK(strcmp(nr.p[0].osm, "way/4242") == 0 && !nr.p[0].name[0],
+ "the nearest: %s", nr.p[0].osm);
+ struct mp_place at;
+ place(&at, "Trapani", 38.0175, 12.515);
+ struct janas_buf d = {0};
+ mp_near_data(&d, &at, "pharmacy", 1, &nr);
+ const char *t = fill(MP_NEAR_LAYOUT, &d);
+ CHECK(strstr(
+ t,
+ "Within 1 km of Trapani: 5 pharmacies; these are the 5 nearest:\n"
+ "1. (no name) - 10 m ") == t &&
+ strstr(t, "; open: Mo-Sa 08:30-13:00,16:30-20:00\n") &&
+ strstr(t, "Via della Cuba 37"),
+ "the pharmacies:\n%s", t);
+ janas_buf_free(&d);
+ static const char busy[] =
+ "<?xml version=\"1.0\"?>\n<p><strong>Error</strong>: runtime error: "
+ "Dispatcher_Client::request_read_and_idx::timeout. The server is "
+ "probably too busy to handle your request. </p>";
+ CHECK(mp_read_overpass(busy, strlen(busy), 38, 12, 10, &nr, err,
+ sizeof err) == -1 &&
+ strstr(err, "too busy now"),
+ "Overpass, too busy: %s", err);
+ /* every kind has its words */
+ for (size_t i = 0; i < MP_N_KINDS; i++) {
+ char w[64];
+ snprintf(w, sizeof w, "\nwhat.%s = ", MP_KINDS[i].name);
+ CHECK(strstr(MP_NEAR_LAYOUT, w), "no words for %s", MP_KINDS[i].name);
+ }
+}
+
+static void places(void)
+{
+ struct mp_place p;
+ CHECK(mp_read_nominatim(NOMINATIM, strlen(NOMINATIM), &p) == 0 &&
+ strcmp(p.name, "Stazione Centrale") == 0 &&
+ strcmp(p.city, "Palermo") == 0 &&
+ strcmp(p.osm, "way/381762269") == 0 &&
+ strcmp(p.kind, "railway=platform") == 0 &&
+ fabs(p.lat - 38.1101703) < 1e-7,
+ "Nominatim: %s, %s, %s", p.name, p.city, p.osm);
+ CHECK(mp_read_nominatim("[]", 2, &p) == -1, "Nominatim, nothing found");
+ struct mp_place rev;
+ CHECK(mp_read_nominatim(NOMINATIM + 1, strlen(NOMINATIM) - 2, &rev) == 0 &&
+ strcmp(rev.name, "Stazione Centrale") == 0,
+ "Nominatim's reverse lookup, one place");
+ struct janas_buf d = {0};
+ mp_find_data(&d, &p);
+ const char *t = fill(MP_FIND_LAYOUT, &d);
+ CHECK(strstr(t, "Stazione Centrale:\n- address: Stazione Centrale, Via "
+ "Paolo Balsamo") == t &&
+ strstr(t, "- on the map: https://www.openstreetmap.org/?mlat="
+ "38.11017&mlon=13.36805#map=17/38.11017/13.36805\n"),
+ "the place:\n%s", t);
+ janas_buf_free(&d);
+ CHECK(mp_read_nominatim(TOWN, strlen(TOWN), &p) == 0 &&
+ fabs(p.lat - 38.0173961) < 1e-7 &&
+ strcmp(p.osm, "relation/39150") == 0,
+ "a town by its point, not its boundary's: %f", p.lat);
+ CHECK(mp_read_photon(PHOTON, strlen(PHOTON), &p) == 0 &&
+ strcmp(p.name, "Via Michelangelo Fardella") == 0 &&
+ strcmp(p.city, "Trapani") == 0 &&
+ strcmp(p.osm, "way/105508402") == 0 &&
+ fabs(p.lon - 12.5253913) < 1e-7,
+ "Photon: %s, %s, %s", p.name, p.city, p.osm);
+}
+
+int main(void)
+{
+ setenv("TZ", "UTC", 1);
+ routes();
+ transit();
+ near();
+ places();
+ if (failures) {
+ printf("test_maps_parse: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_maps_parse: ok\n");
+ return 0;
+}