Inland Water API
Доступ & обмеженняPublic, no key needed · Heavy▾
Відкрито для всіх. Безплатний ключ API з вашого профілю розширює обмеження: надішліть його у X-API-Key заголовок, або як api_key= в адресі.
| 5 хвилин | Година | День | |
|---|---|---|---|
| Без ключа | 20 | 120 | 500 |
| З ключем | 60 | 400 | 2,000 |
Each 100 square km of area counts as one request, so a 10 km square is 1 and a 30 km square is 9.
Увійдіть, щоб створити безплатний ключ на сторінці свого профілю.
Кожна відповідь несе X-RateLimit-Remaining та X-RateLimit-Reset. Якщо перевищити ліміт, результат — помилка 429 з retry_after за секунди. Відхилені запити не враховуються.
Де вода перевищує область навколо точки, і що саме: кожна комірка приблизно 10 метрів повертається як загальна вода (озера, водосховища, пруди, річки, канали та море вздовж узбережжя), ручай, яр, дренаж або сухе, ті самі дані що Карта внутрішніх водойм малює. Запитайте як JSON для веб-сторінки або скрипту, або як невеликий двійковий файл, який можуть мати польотний комп'ютер або наземна станція, щоб вода на місці запуску була вбудована у прошивку замість завантаження в день запуску.
lat lon size_kmПараметри
| Параметр | Значення |
|---|---|
lat, lon | Середина квадрата, десяткові градуси (lng також прийнято) |
size_km | Сторона квадрата в км, більше 0 і до 30. Якщо не вказано, 1. Квадрати над 10 км поступають як format=bin tylko. |
format | Опціонально. json (за замовчуванням для квадратів до 10 км): комірки як base64 всередину відповіді JSON з усім необхідним для їх читання. bin: заголовок з 32 байтів та комірки, як файл, для будь-якого розміру. |
compress | Опціонально. none (за замовчуванням), zlib або lzma. З format=bin the whole file is compressed; with json комірки перед base64. lzma це LZMA-alone (.lzma) з словником розміром 64 КБ, точно як Tree Canopy API dává to. |
classes | Опціонально. Класи, які потрібно зберегти, як список, наприклад, 1,2; every other class comes back as 0. Left out, all three. |
download | Опціонально. 1 sprawi, że przeglądarka zapisze format=bin відповідь як файл з назвою для квадрата. |
The classes
| Class | What | From |
|---|---|---|
| 0 | Dry | |
| 1 | General water | ESA WorldCover's permanent water; OpenStreetMap's lakes, ponds, reservoirs, marina basins and river areas; rivers and canals mapped as lines; the sea along the coast |
| 2 | Streams and becks | OpenStreetMap waterway=stream |
| 3 | Ditches and drains | OpenStreetMap waterway=drain and ditch |
Any cell with water in it at all takes its class, however little: a stream a metre wide comes back as an unbroken line of cells. That is meant for hazard checks, where a cell with any water in it is a place something can land wet. Where two classes meet in a cell the worse is kept, 1 over 2 over 3, so a stream running into a lake is part of the lake. Many ditches and drains are dry for much of the year, and streams and drains that pass through culverts may show as open where they are not; classes=1,2 leaves ditches and drains out.
The satellite part gives the same quality worldwide; the OpenStreetMap part fills in what the satellite cannot see, such as shaded rivers, crowded marinas and anything narrower than a cell, but only has what has been mapped. The satellite water is as it stood in 2021.
The cells
The grid is the water store's own, so nothing is resampled: each cell is exactly 1/12000 of a degree each way, about 9.3 m north to south and, at UK latitudes, about 5.5 m east to west. Рядок 0 — північний край, стовпець 0 — західний край; rows run south and columns east. Each cell is два біти, його клас, клітинки розташовані впритул один до одного вздовж рядка, перша клітинка в найстарших бітах, тому чотири комірки заповнюють кожен байт. Кожен рядок починається на цілому байті, тому рядок j починається з байта j * row_bytes.
Ground not yet in the database is 0 as well; the JSON answer's coverage_pct показує, скільки квадрата утримує база даних, water_pct скільки з неї води з збережених класів, та class_pct скільки коштує кожен клас. За межами морських даних WorldCover не має жодної інформації про воду: відкрите море походить з рельєфу, земля на рівні або нижче за 0 м.
Розміри
На широтах Великої Британії (54°N) перед стисненням:
| Квадрат | Комірки | Файл |
|---|---|---|
| 1 км | 108 × 186 | 5,0 КБ |
| 3 км | 324 × 556 | 44 КБ |
| 5 км | 540 × 926 | 122 КБ |
| 10 км | 1,078 × 1,850 | 487 KB |
| 20 км | 2 156 × 3 700 | 1,9 МБ |
| 30 км | 3 234 × 5 550 | 4,3 МБ |
Більша частина земель суха, тому стиск зменшує їх значно: квадрат з кількома озерами та струмками звичайно стискається до невеликої частини свого вихідного розміру, та lzma є найменшим.
Двійковий файл
З format=bin: a 32 byte header, little endian, then the rows, north first. It is the same layout as the tree canopy and roads files, so one reader handles all three; only the name, the version and the bits a cell differ.
| Байт | Тип | Значення |
|---|---|---|
| 0 | char[4] | ACWT |
| 4 | uint8 | Версія, 2 |
| 5 | uint8 | Біти на клітину, 2 |
| 6 | uint16 | Комірок на градус, 12000 |
| 8 | int32 | Північний край в клітинах: його широта × 12000 |
| 12 | int32 | Західний край в комірках: його довгота × 12000 |
| 16 | uint32 | Рядки |
| 20 | uint32 | Колонки |
| 24 | uint32 | Байтів на рядок |
| 28 | uint32 | 0, зарезервовано |
Краї мають цілі числа комірок, тому позиція відповідає її комірці точно: рядок north_edge - 1 - floor(lat * 12000), стовпець floor(lon * 12000) - west_edge.
Приклади
https://www.altimetercloud.com/api/water/?lat=54.35&lon=-2.95&size_km=3
https://www.altimetercloud.com/api/water/?lat=54.35&lon=-2.95&size_km=5&classes=1,2&format=bin&compress=zlib
https://www.altimetercloud.com/api/water/?lat=54.35&lon=-2.95&size_km=10&format=bin&compress=lzma&download=1
Відповідь JSON
{
"success": true,
"lat", "lon", "size_km", "bits", bits is 2
"rows", "cols", "cells", "row_bytes", the grid, as above
"cells_per_degree", "north_edge_cell", "west_edge_cell",
"north", "south", "west", "east", the square's edges, degrees
"cell_deg", "cell_m_north_south", "cell_m_east_west",
"water_pct", cells with water of the classes kept
"class_pct": { "1": ..., "2": ... }, each class kept
"classes": { "1": "general water", ... },
"kept": [1, 2, 3], the classes asked for
"coverage_pct", cells the database holds
"meaning", "order", "compress", "bytes",
"data_b64", the rows, row 0 first, compressed if asked
"file_name", "seconds",
"credits": { "water", "source", "doi", "licence", "full" }
}
Reading the cells
On a device: what water is below me
Give a position and get the class of the cell it is in. The file sits in flash or on a card, and cells is the bytes straight after the 32 byte header. Use doubles for the position.
// C
typedef struct __attribute__((packed)) {
char magic[4]; // "ACWT" (roads "ACRD", trees "ACTR")
uint8_t version; // 2
uint8_t bits; // 2
uint16_t cells_per_deg; // 12000
int32_t north_edge; // latitude of the north edge * 12000
int32_t west_edge; // longitude of the west edge * 12000
uint32_t rows, cols, row_bytes, reserved;
} GridHeader;
// the class at a position, 0 to 3, or -1 outside the square
int waterClassAt(const GridHeader *h, const uint8_t *cells, double lat, double lon) {
int32_t j = h->north_edge - 1 - (int32_t)floor(lat * h->cells_per_deg);
int32_t i = (int32_t)floor(lon * h->cells_per_deg) - h->west_edge;
if (j < 0 || i < 0 || j >= (int32_t)h->rows || i >= (int32_t)h->cols) return -1;
uint8_t b = cells[(uint32_t)j * h->row_bytes + (i >> 2)];
return (b >> (6 - 2 * (i & 3))) & 3; // four cells a byte, first in the top bits
}
Вода біля мене
Для приземлення пройдіть по клітинкам, центри яких знаходяться в радіусі, виміряному в метрах від розміру клітинки: 111320 / 12000 м з півночі на південь, і це помножено на косинус широти з заходу на схід. Найгірший клас в колі, частка комірок, що є водою, і найменша відстань до кожного класу походять з одного проходу.
double ch = 111320.0 / h->cells_per_deg, cw = ch * cos(lat * M_PI / 180.0);
int ny = (int)(radius_m / ch) + 1, nx = (int)(radius_m / cw) + 1, wet = 0, all = 0;
double nearest[4] = { -1, -1, -1, -1 }; // by class
for (int dy = -ny; dy <= ny; dy++)
for (int dx = -nx; dx <= nx; dx++) {
double d = sqrt((dx * cw) * (dx * cw) + (dy * ch) * (dy * ch));
if (d > radius_m) continue;
int c = waterClassAt(h, cells, lat + dy / (double)h->cells_per_deg, lon + dx / (double)h->cells_per_deg);
if (c < 0) continue;
all++;
if (c) { wet++; if (nearest[c] < 0 || d < nearest[c]) nearest[c] = d; }
}
Розпаковування на мікроконтролері
Стиснення те саме, що і файли полога дерева: compress=lzma розпаковується з LzmaDecode() від LZMA SDK та на ESP32 compress=zlib не потребує нічого додаткового, оскільки miniz tinfl знаходиться в його ROM. Див. Розпаковування на мікроконтролері на сторінці Tree Canopy.
На комп'ютері
# Python
import requests, struct, zlib, numpy as np
r = requests.get('https://www.altimetercloud.com/api/water/',
params={'lat': 54.35, 'lon': -2.95, 'size_km': 3, 'format': 'bin', 'compress': 'zlib'})
f = zlib.decompress(r.content) # or lzma.decompress(r.content, format=lzma.FORMAT_ALONE)
magic, ver, bits, cpd, north, west, rows, cols, rb, _ = struct.unpack('<4sBBHiiIIII', f[:32])
b = np.unpackbits(np.frombuffer(f[32:], np.uint8).reshape(rows, rb), axis=1)[:, :cols * 2]
water = (b[:, 0::2] << 1) | b[:, 1::2] # rows x cols, 0 dry, 1 water, 2 stream, 3 ditch
lat_of_row = lambda j: (north - j - 0.5) / cpd
lon_of_col = lambda i: (west + i + 0.5) / cpd
Помилки
Помилки повертаються як JSON с "success": false, код і повідомлення.
| Код | Значення |
|---|---|
412 | A parameter is missing or not valid, the square is more than 30 km, JSON was asked for over 10 km, or classes= is not a list of 1 to 3 |
413 | Квадрат має занадто багато комірок, що трапляється лише дуже близько до полюсів |
429 | Занадто багато запитів з вашої адреси або один все ще обробляється |
501 | Запитана компресія зараз недоступна |
Спробуйте
Те Inland Water Map has a download panel: move the map so the cross sits on your launch site, choose the size and compression, and it saves the file from this API.
Water data credits
© ESA WorldCover project 2021 / Contains modified Copernicus Sentinel data (2021) processed by ESA WorldCover consortium. ESA WorldCover 10 m 2021 v200, Zanaga, D. et al. 2022, doi:10.5281/zenodo.7254221, licensed under CC BY 4.0.
Contains OpenStreetMap data © OpenStreetMap contributors, available under the Open Database Licence (ODbL).
The two are combined here and reduced to a water class a cell, which changes them: this is not the original data of either.
Licence of this data. Because it contains OpenStreetMap data, the data this API gives out is made available under the Open Database License (ODbL) 1.0. You may use it freely, commercially too, as long as you credit it as above and share any database you make from it under the same licence.
Кредитування AltimeterCloud
Безкоштовно. Якщо ви використовуєте this API, or anything made from the answers, in a commercial product or service, credit AltimeterCloud with a link to www.altimetercloud.com в точці використання: на екрані, сторінці або надрукованому вигляді, де з'являються дані, наприклад “Data from AltimeterCloud.com”. До того ж, застосовуються всі кредити, які запитують власні джерела даних, перелічені на цій сторінці.



















