Uk:Overpass API/Overpass QL

From OpenStreetMap Wiki
Jump to navigation Jump to search
Overpass API logo.svg
edit
Overpass API · Language reference · Language guide · Technical terms · Areas · Query examples · Sparse Editing · Permanent ID · FAQ · більше (українська) · Web site
Servers status · Versions · Development · Technical design · Installation · XAPI compatibility layer · Public transport sketch lines · Applications · Source code and issues
Overpass turbo · Wizard · Overpass turbo shortcuts · MapCSS stylesheets · Export to GeoJSON · більше (українська) · Development · Source code and issues · Web site
Overpass Ultra · Overpass Ultra extensions · MapLibre stylesheets ·більше (українська) · Source code and issues · Web site

Overpass QL (скорочено від «Overpass Query Language») це друга мова запитів яку створили для Overpass API, першою була Overpass XML. Overpass QL це  процедурна  імперативна мова програмування що написана у стилі  синтаксису мови C.

Цю вікі-сторінку написано з наміром створити повну технічну довідку до структури Overpass QL. Якщо вам потрібна колекція практичних прикладів перейдіть на вікі-сторінку Overpass API у прикладах – вона буде зрозумілішою для людей без технічного досвіду.

Огляд мови

Вказівки

Сирці Overpass QL розподілені на вказівки, і кожна вказівка закінчується крапкою з комою ;. Вказівки виконуються послідовно у  процесі, і кожна вказівка робить зміни до стану виконання процесу.

Стан виконання

Стан виконання Overpass QL складається з:

  • Набору за замовчуванням _ (нижня риска)
  • іншого іменованого набору, якщо його створив користувач
  •  Стеку — під час виконання складених вказівок Overpass QL.

Набори

Overpass QL оперує наборами. Результати виконання вказівок записуються у набори, а наступні в черзі вказівки зчитують ці набори уже як вхідні. Набір Overpass QL може містити будь-яку комбінацію (і будь-яку кількість) точок, ліній, звʼязків та заповнених полігонів утворених із елементів OpenStreetMap.

Поки ви не вкажете іменований набір як вхідний чи підсумковий, всі вхідні чи вже оброблені дані неявно зчитуються з (чи записуються до) набору за замовчуванням що має назву _ (символ нижньої риски). Як тільки новий результат явно чи неявно призначається до набору що існує, попередній вміст такого набору більше не буде доступний тому що буде замінений новим вмістом. Набори Overpass QL завжди мають глобальну  область видимості.

Наприклад, ось такий код:

  node[name="Foo"];

неявно записує результат теґового запиту name="Foo" до набору за замовчуванням _, перезаписуючи будь-який попередній вміст цим результатом. Результат можна записати до специфічного набору якщо використати синтаксис ->, де назва набору починатиметься з символу крапки .. Таким чином, наведена вище вказівка еквівалентна до вказівки:

  node[name="Foo"]->._;

Так само й така вказівка:

 (
  node[name="Foo"];
  node[name="Bar"];
 );

обʼєднує результат двох теґових запитів у вказівку обʼєднання, а потім надсилає результат до набору за замовчуванням _. Це еквівалентно до:

 (
  node[name="Foo"];
  node[name="Bar"];
 )->._;

Щоб записати елементи до іменованого набору, знову ж таки, використайте синтаксис ->, а за ним назву набору. Наприклад, такий запит:

  (node[name="Foo"];)->.a;

запише всі елементи-точки з теґом name=Foo у набір з назвою a. Після виконання цього запиту у вас утвориться два набори: набір a, лише з однією точкою, та набір _ який не змінювався.

Назви наборів можуть містити букви, цифри та нижню риску, але не повинні починатися з цифри.

Щоб прочитати елементи з набору, додайте . і назву набору до команди.

  node.a[amenity=foo];

поверне всі точки з іменованого набору a що мають ключ amenity зі значенням foo.

Структура мови

Є кілька різних типів вказівок Overpass QL. Вони згруповані в:

  • Налаштування — необовʼязкові глобальні змінні, які потрібно записувати у першій вказівці запиту. Прикладами налаштувань є таймаут для сервера Overpass API та формат вихідних даних після виконання запиту Overpass QL.
  • Складені вказівки: Складені вказівки групують вказівки Overpass QL разом, щоб дозволити  дизʼюнкцію (тести на істинність), а також цикли.
  • Автономні запити: Це повні вказівки самі по собі. Вони можуть, наприклад, звертатися із запитом до сервера Overpass API щоб створити набір; або ж надсилати результат виконання запиту до якогось місця. Автономні запити складаються з менших компонентів мови Overpass QL, таких як оцінювачі, фільтри та оператори.

Дужки

У синтаксисі QL використовуються круглі дужки (), квадратні дужки [] та фігурні дужки {}. На цій сторінці з документацією під терміном дужки мають на увазі квадратні дужки. Якщо бажаєте, почитайте Вікіпедію щоб розібратися з номенклатурою.

Налаштування

Налаштування Overpass QL мають бути задекларовані у першій незакоментованій вказівці у сирцевому коді Overpass QL. Налаштування не можуть бути задекларованими у кількох вказівках.

Декларації налаштувань беруть у дужки []. Двокрапку : ставлять між назвою налаштування і значенням або значеннями які мають бути застосованими. Вказівка з налаштуваннями має закінчуватися крапкою з комою ;.

// Типовий рядок із декларацією налаштувань
// для сервера Overpass Turbo
[out:json][timeout:25];

timeout:

Налаштування timeout: має один параметр — невідʼємне ціле число. Типове значення — 180.

Цей параметр вказує на максимально дозволений час виконання запиту в секундах, якого очікує користувач. Якщо запит виконується довше ніж цей вказаний час, сервер може перервати запит. Зворотнім ефектом є те, що чим вищим буде це значення, тим більшою буде ймовірність того, що сервер відхилить запит не виконуючи його.

Отже, якщо ви надсилаєте по-справжньому складний і великий запит, задекларуйте для нього більше значення; наприклад, «3600» для години. Також переконайтеся, що ваш клієнт досить терплячий, щоб дочекатися виконання запиту і не перервати його через власний таймаут.

Приклад:

  [timeout:180]

Ліміт елементів (maxsize:)

Налаштування maxsize: має один параметр — невідʼємне ціле число. Типове значення — 536870912 (512 Мб).

Цим параметром зазначають максимально дозволену для запиту кількість оперативної памʼяті сервера в байтах, яку очікує користувач. Якщо запит потребує більше оперативної памʼяті, ніж це значення, сервер може перервати запит за вичерпанням памʼяті. Зворотнім ефектом є те, що чим вищим є це значення, тим більшою буде ймовірність того, що сервер відхилить ваш запит не виконуючи його.

Отже, якщо ви надсилаєте дійсно складний великий запит, додайте до нього більше значення; наприклад, «1073741824» для гігабайту. Максимальне значення дуже залежить від поточного навантаження на сервер, наприклад, запити на 2 Гб, ймовірно, будуть відхилені в пікові години, оскільки вони не вписуються в загальне управління ресурсами. Якщо висловитися технічною мовою, maxsize розглядається як 64-бітний знаковий номер.

Приклад:

  [maxsize:1073741824]

Важливе зауваження: Нещодавно був введений новий механізм для переривання запитів, що перевищують обсяг у 2 Гб. Такий розмір цього ліміту все ще обговорюється і може змінитися з часом. Якщо ви отримуєте повідомлення у якому написано щось на кшталт «runtime error: query run out of memory using about 2048 MB of RAM.», перечитайте цей тред також.

Формат вихідних даних (out:)

Глобальне налаштування out: не повʼязане зі вказівкою out. Синтаксис не повинен змішуватися.

Налаштування out вказує у якому форматі видавати дані OpenStreetMap після виконання запиту. Значення може бути одним із пʼяти; типове значення — xml:

  • xml
  • json (не плутати з geoJSON)
  • csv
  • custom
  • popup

Приклад:

  [out:json]

Вихідні дані у форматі CSV

Вихідний формат CSV видає дані з OpenStreetMap у вигляді csv-документу, який можна одразу відкрити у програмах на кшталт LibreOffice. Для нього треба налаштувати додаткові параметри щоб підписати список полів які мають бути показані, а також два необовʼязкові параметри: щоб показати чи приховати рядок із заголовками стовпців таблиці та щоб обрати символ з допомогою якого значення розділятимуться по окремих стовпцях.

Формат:

  [out:csv( fieldname_1 [,fieldname_n ...] [; csv-headerline [; csv-separator-character ] ] )]

Нотатки:

  • Числові значення (координати, ідентифікатори) записуються без поділу на розряди. У геометричних координатах десятковим роздільником є символ крапки ..
  • Специфічні символи у рядках не екрануються. Це зміниться з випуском версії 0.7.55.
  • Символ роздільника за замовчуванням (Tab) все ще має дозволяти більшу частину часу аналізувати табличні дані без відсутніх, зламаних чи помилкових стовпців.
  • Такі налаштування CSV все ще можуть не відповідати тому, чого очікує ваша програма електронних таблиць (зокрема, десятковий роздільник у неанглійських версіях). Якщо ви відкриєте файл CSV безпосередньо за допомогою своєї програми, і дані здаватимуться пошкодженими або нерозбірливими: імпортуйте дані в текстовий стовпець нової електронної таблиці та перетворіть їх у табличні дані всередині цієї програми, використовуючи власні налаштування; або використовуйте зовнішній фільтрувальний скрипт, щоб перетворити файл перед тим як відкривати його.
Простий приклад

[out:csv(name)] видаватиме лише теґ name. Нижче перегляньте складніші приклади.

Список з назвами полів

Окрім звичайних імен полів OpenStreetMap — теґів, для кожного елемента в підсумковому наборі доступні спеціальні поля. Зверніть увагу, що всі ці спеціальні назви полів мусять починатися з двох двокрапок ::.

Спеціальні назви полів Опис
::id Ідентифікатор обʼєкта OpenStreetMap
::type Тип обʼєкта OpenStreetMap: точка, лінія, звʼязок
::otype Обʼєкт OpenStreetMap як числове значення
::lat Широта (доступна для точок, або в режимі out center)
::lon Довгота (доступна для точок, або в режимі out center)
Дані поля доступні тільки якщо для виведення елементів OpenStreetMap використано режим out meta;
::version Номери версій обʼєктів OpenStreetMap
::timestamp Часова мітка що показує коли востаннє було змінено обʼєкт OpenStreetMap
::changeset Номер набіру змін у якому обʼєкт було змінено
::uid Ідентифікатор учасника OpenStreetMap
::user Імʼя учасника OpenStreetMap
Дані поля доступні тільки якщо для виведення елементів OpenStreetMap використано режим out count;
::count Рахує загальну кількість обʼєктів (точок, ліній, звʼязків та полігонів) у вхідному наборі
::count:nodes Рахує кількість точок у вхідному наборі
::count:ways Рахує кількість ліній у вхідному наборі
::count:relations Рахує кількість звʼязків у вхідному наборі
::count:areas Рахує кількість полігонів у вхідному наборі

Приклад:

  [out:csv(
    ::"id", amenity, name, operator, opening_hours, "contact:website", "contact:phone", brand, dispensing, lastcheck
  )];

Залізничні станції у місті Бонн:

try it yourself in overpass-turbo
[out:csv(::id,::type,"name")];
area[name="Bonn"];
nwr(area)[railway=station];
out;
Заголовки стовпців у форматі CSV

Наявність чи відсутність рядку із заголовками може контролюватися першим необовʼязковим параметром, який можна додати одразу після списку полів та крапки з комою. Можливими значеннями є true або false. Типове значення true.

  [out:csv(
    ::"id", amenity, name, operator, opening_hours, "contact:website", "contact:phone", brand, dispensing, lastcheck;
    false
  )];
Символ яким розділені значення у форматі CSV

За замовчуванням усі поля розділяються символом табуляції \t. Але це налаштування можна змінити якщо вказати другий необовʼязковий параметр. У прикладі нижче всі вихідні поля будуть, натомість, розділені символом «пайп» |.

  [out:csv(
    ::"id", amenity, name, operator, opening_hours, "contact:website", "contact:phone", brand, dispensing, lastcheck;
    true; "|"
  )];
Перевірка вихідних даних у форматі CSV на повноту

На відміну від режимів виведення даних у форматі XML та JSON, для формату CSV немає жодного позначення чи повідомлення про помилковий результат. Пустий результат, або результат лише із рядком заголовків може свідчити про те що потрібних обʼєктів не було знайдено взагалі, або ж про те що запит було відхилено через таймаут або через якусь серйознішу помилку. Один зі способів обійти таку поведінку — додати лічильник, що рахуватиме кількість обʼєктів з попереднього підсумкового набору. Таку вказівку завжди треба дописувати вкінці запиту.

Приклад нижче розширює показаний раніше список усіх залізничних станцій у місті Бонн додатковою вихідною вказівкою. Ця вказівка створює додатковий підсумковий стовпець у даних формату CSV та додає псевдо-елемент з типом «count». Кількість елементів буде записана у останньому задекларованому стовпці ::count, і для рядків зі звичайними даними значення залишиться пустим:

  [out:csv(::type,::id,"name",::count)];
  area[name="Bonn"]->.a;
  ( node(area.a)[railway=station];
    way(area.a)[railway=station];
    rel(area.a)[railway=station];
  );
  out;
  out count;

Вихідний результат тепер містить додатковий стовпець з типом ::count і вказаною загальною кількістю елементів, що містяться у поточному підсумковому наборі: 5. Якщо фінальний рядок відсутній або загальна кількість відрізняється, можете бути впевнені що щось пішло не так і результат запиту неповний чи непослідовний.

@type 	@id        	name               	@count
node  	  26945519 	Bonn-Oberkassel    	      
node  	1271017705 	Bonn-Beuel         	      
node  	2428355974 	Bonn-Bad Godesberg 	      
node  	2713060210 	Bonn Hauptbahnhof  	      
node  	3400717493 	Bonn-Mehlem        	      
count 	         0 	                   	     5

Значення custom і popup також вимагають подальшого налаштування. Щоб дізнатися про це детальніше, будь ласка, прочитайте документацію вихідних форматів.

Глобальний обмежувальний прямокутник (bbox)

«Обмежувальний прямокутник» визначає ділянку мапи щодо обʼєктів якої буде здійснено запит. Глобальне налаштування bbox може бути використане щоб визначити обмежувальний прямокутник який буде неявно застосовуватись в усіх вказівках (хіба що в одній із вказівок буде свій власний bbox). Якщо жодного bbox не вказано, його стандартне значення — «обʼєкти по всьому світу».

У стандартній програмі Overpass QL обмежувальний прямокутник утворюється з двох пар десяткових дробів — координат у градусах у порядку та форматі за стандартом ISO 6709, де кожне значення координати відділене від наступного комою. Значення вказані у порядку: найпівденніша широта, найзахідніша довгота, найпівнічніша широта, найсхідніша довгота.

[bbox:south,west,north,east]
// Обмежувальний прямокутник навколо німецького міста Бонн
[bbox:50.6,7.0,50.8,7.3]
// Обмежувальний прямокутник навколо частини міста Ріо-де-Жанейро
[bbox:-23,-43.3,-22.8,-43.1]

Нотатка: Коли запит кодується у вигляді URL як значення параметра data=, обмежувальний прямокутник може також додаватися як окрема змінна bbox. Якщо йти таким шляхом, порядок координат змінюється на протилежний, довгота—широта. (Це типовий порядок для OpenLayers та інших фреймворків.)

У прикладі з містом Бонн, що вище, URL-кодування буде таким:

  /api/interpreter?data=[bbox];node[amenity=post_box];out;&bbox=7.0,50.6,7.3,50.8

Так буде знайдено всі поштові скриньки в німецькому місті Бонн та на його околицях що потрапили у обмежувальний прямокутник.

Дата

date це глобальне налаштування що змінює запит Overpass QL так, щоб він досліджував attic-дані, і показав результат на основі такої версії бази даних OpenStreetMap якою вона була у зазначену конкретну дату. Це налаштування буде корисне, наприклад, щоб відновити дані які були пошкоджені вандалізмом, або просто щоб подивитися на те яким обʼєкт був у базі даних у якийсь специфічний момент минулого.

Налаштування складається з ідентифікатора date, за яким іде двокрапка :, а потім дата що записана у форматі бази даних OpenStreetMap за стандартом ISO 8601 що взята у лапки, у вигляді РРРР-ММ-ДДTгг:хв:ссZ.

Ось приклад запиту до бази даних, якою вона була станом на 28 жовтня 2015 року о 19:20:00 часового поясу UTC:

[date:"2015-10-28T19:20:00Z"]

У базі даних OpenStreetMap не існує attic-даних з датою що була раніше за 2012-09-12T06:55:00Z (1347432900 секунда від початку епохи). Ця дата показує момент коли ODbL-сумісний файл планети було змінено вперше. Використовувати налаштування date що була раніше технічно можливо, але якщо це зробити все одно результатом буде база даних станом на 2012-09-12T06:55:00Z.

Різниця між двома датами (diff)

Налаштування diff дозволяє визначити різницю між двома запитами у різні часові точки існування бази даних. Це корисно, наприклад, щоб визначити дельту для витягів з бази даних.

Налаштування складається з ідентифікатора diff, за яким іде двокрапка : , а потім дата що записана у форматі бази даних OpenStreetMap за стандартом ISO 8601 що взята у лапки, у вигляді РРРР-ММ-ДДTгг:хв:ссZ, і необовʼязкові кома та друга дата. Якщо другу дату не вказувати — типове значення «зараз».

Приклад:

[diff:"2012-09-14T15:00:00Z"]

Таке налаштування запустить обробку решти запиту так неначе він був відправлений до бази даних о 15:00 14 вересня 2012 року, потім запустить той самий запит з поточною датою. Підсумковим результатом будуть вихідні дані що є різницею між результатами виконання двох попередніх запитів.

[diff:"2012-09-14T15:00:00Z","2012-09-21T15:00:00Z"]

Якщо додати таке налаштування, відбудеться, практично, те ж саме що й минулого разу, але порівнюватимуться дані станом на 14 вересня та дані станом на 21 вересня.

Зауважте, що підсумковий результат не включатиме жодних проміжних версій, які могли існувати між першою та останньою часовими мітками. Тобто, якщо є кілька змін якогось обʼєкта, буде повернена лише остання версія із заданого часового проміжку.

Розширена різниця між двома датами (adiff)

Налаштування adiff робить практично те ж саме що й diff , але для всіх елементів що не містяться у новішому результаті буде вказано що саме з ними відбулося.

Якщо елемент було видалено, то дата його видалення буде виведена із позначкою «visible=false». Якщо елемент було змінено так що він більше не збігається із запитом то дата його змінення буде виведена із позначкою «visible=true».

Щоб дізнатися більше прочитайте: Augmented Diffs.

Складені вказівки

Обʼєднання

Складена вказівка обʼєднання записується всередині пари круглих дужок. Всередині вказівки обʼєднання можна розмістити будь-яку послідовність інших вказівок, включно з вкладеним обʼєднанням та вказівками foreach. Зауважте що квадратні дужки [ ... ] що показані нижче позначають необовʼязкові частини синтаксису і їх не треба передруковувати буквально.

  (statement_1; statement_2; )[->.result_set];

Складена вказівка обʼєднання не зчитує жодного вхідного набору. Вона продукує підсумковий набір який є обʼєднанням підсумкових наборів усіх підвказівок, незалежно від того чи мають підвказівки перенаправлений підсумковий набір чи ні.

Приклад:

  (node[name="Foo"]; way[name="Foo"];);

Перша вказівка вибирає всі точки що мають назву «Foo»; друга вказівка вибирає всі лінії що мають назву «Foo». Після вказівки обʼєднання у підсумковому наборі зберігається обʼєднання підсумкових наборів елементів від обох вкладених усередину вказівок.

Підсумковий набір вказівки обʼєднання можна перенаправити вже звичним для нас постфікс-нотуванням.

Приклад:

  (node[name="Foo"]; way[name="Foo"];)->.a;

Це той самий приклад, але результат буде записано до змінної a.

Обмеження: Зауважте що вказівки foreach та print не можуть бути піделементами елементу union.

Різниця

Складена вказівка різниці записується всередині пари круглих дужок. Усередині вказівки обʼєднання, треба помістити рівно дві вказівки, та розділити їх мінусом. Зауважте що квадратні дужки [ ... ] що показані нижче позначають необовʼязкові частини синтаксису і їх не треба передруковувати буквально.

  (statement_1; - statement_2;)[->.result_set];

Складена вказівка різниці не зчитує жодного вхідного набору. Вона продукує підсумковий набір який містить усі елементи що є результатом виконання першої підвказівки і не містить тих елементів що є результатом виконання другої підвказівки.

Приклад:

  (node[name="Foo"]; - node(50.0,7.0,51.0,8.0););

Така вказівка вибере всі точки що мають назву «Foo» але не всередині вказаного обмежувального прямокутника.

Підсумковий набір вказівки різниці можна перенаправити вже звичним для нас постфікс-нотуванням.

Приклад:

  (node[name="Foo"]; - node(50.0,7.0,51.0,8.0);)->.a;

Це той самий приклад, але результат буде записано до змінної a.

Перетин

Також можна створити набір елементів, які зʼявляються в обох вхідних наборах, тобто елементів, які є частиною обох наборів. Це описується нижче у розділі За вхідним набором (.setname):

  node.a.b;

Це не складена вказівка, але її розміщено тут через те що вона схожа на вказівку різниці яку було описано вище.

Складена вказівка if

since v0.7.55

Складена вказівка if виконає свої підвказівки тільки якщо її умова буде оцінена як булева істина. Це дозволяє, наприклад, спробувати ширші умови для пошуку, якщо вужчі умови не спрацювали.

Вказівка не взаємодіє з жодним з наборів безпосередньо.

Базовий синтаксис такий:

 if (<Evaluator>)
 {
   <List of Substatements>
 }

і, відповідно, такий:

 if (<Evaluator>)
 {
   <List of Substatements>
 }
 else
 {
   <List of Substatements>
 }

Де <Evaluator> це оцінювач а <List of Substatements> це список підвказівок.

Цикл по кожному з елементів (foreach)

починаючи з версії № 0.7.51

Складену вказівку foreach записують починаючи з ключового слова foreach, за яким іде пара фігурних дужок. Між цими фігурними дужками можна розмістити будь-яку послідовність інших вказівок, включно з вкладеним обʼєднанням та вказівками foreach.

Складена вказівка foreach бере вхідний набір і не продукує жодного підсумкового набору. Складена вказівка foreach проходиться циклічно по вмісту вхідного набору, по одному разу на кожний елемент із вхідного набору.

Приклад:

  way[name="Foo"];
  foreach
  {
    (
      ._;
      >;
    );
    out;
  }

Така вказівка для кожної лінії що має теґ name зі значенням «Foo», виведе точки що належать цій лінії й одразу ж за ними саму лінію. Якщо розглянути детальніше, підсумковий набір що є результатом виконання вказівки way[name="Foo"] стає вхідним набором для foreach. Потім, для кожного елемента із цього вхідного набору тіло циклу виконується один раз. Усередині тіла циклу обʼєднується сам елемент та точки з яких складається цей елемент. Обʼєднання цих елементів виводиться.

Зауважте що під час виконання, кожний виведений піднабір є ітерацією що не залежить від піднаборів виведених у інших ітераціях, що може призвести до дублювання обʼєктів у остаточних вихідних даних (жодне обʼєднання усередині циклу не обчислюється вказівкою out).

Вхідний набір для вказівки foreach можна взяти зі змінної, записаної вже звичним для нас постфікс-нотуванням:

Приклад:

  foreach.a(...);

Така вказівка зациклюється по вмісту набору a замість того щоб брати вміст набору за замовчуванням «_».

Назву змінної до якої треба помістити елемент циклу також можна вказати якщо додати постфікс-нотацію одразу перед відкритою дужкою.

Приклад:

  foreach->.b(...);

Така вказівка передасть елементи по яких проходиться цикл до змінної b. Без цього вказівка foreach не збереже елементи у жоден із наборів.

Приклад як взяти вхідний набір зі змінної і передати набір який змінюється циклом до іншої змінної:

  foreach.a->.b(...);

Зауважте що вхідний набір не може бути змінено циклом. Будь які оновлення набору буде збережено для подальшого використання, але це не змінить кількості ітерацій.

Складена вказівка for

since v0.7.55

Складена вказівка for розділяє свій вхідний набір на піднабори і виконує всі вказівки з тіла циклу по одному разу на кожен піднабір.

Вхідний набір розподіляється так: для кожного елемента оцінюється даний оцінювач, а елементи з однаковим значенням групуються разом. На початку виконання кожного циклу вихідний набір заповнюється відповідним піднабором.

Базовий синтаксис такий

 for (<Evaluator>)
 {
   <List of Substatements>
 }

Вхідний та вихідний набори можна зазначити між ключовим словом for та відкритою дужкою. Тобто, ви зазначаєте вхідний набір

 for.<Name of Input Set> (<Evaluator>)
 {
   <List of Substatements>
 }

або вихідний набір

 for->.<Name of Output Set> (<Evaluator>)
 {
   <List of Substatements>
 }

або обидва набори

 for.<Name of Input Set>->.<Name of Output Set> (<Evaluator>)
 {
   <List of Substatements>
 }

Усередині циклу, значення оцінювача доступне за властивістю val вихідного набору. Тобто, за допомогою рядка

 <Output Set>.val

ви можете отримати доступ до значення виразу для цього циклу.

За допомогою спеціального оцінювача keys(), можна зациклитися по всіх ключах що наявні у піднаборі. Відповідний піднабір для кожного ключа це елементи що мають цей набір ключів. На відміну від звичайного оцінювача, у цьому випадку набори не відрізняються одне від одного.

Складена вказівка complete

since v0.7.55

Складена вказівка complete зациклюється через свої підвказівки аж поки результати петлі не стабілізуються. Вона дозволяє відслідковувати групу слабо або ж тісно повʼязаних елементів таких як всі ділянки шляху з тією самою назвою або ж річкові системи.

Вказівка відправляє акумульовані елементи до свого вихідного набору і на початку виконання кожного циклу, і як вихідні дані всієї вказівки повністю.

Елементи акумулюються із вхідного набору перед входом до циклу і знову з вхідного набору у кінці циклу. Якщо вхідний набір містить додаткові елементи то цикл буде виконано ще раз.

Базовий синтаксис такий

 complete
 {
   <List of Substatements>
 }

де <List of Substatements> це список підвказівок.

Максимальне число циклів за замовчуванням — 4096. Це значення можна змінити на будь-яке між 1 та 1048576 для такого циклу. Щоб зробити це введіть бажане значення у круглі дужки одразу після ключового слова «complete»:

 complete(<Number>)
 {
   <List of Substatements>
 }

Вхідний та вихідний набори можна зазначити між ключовим словом complete та відкритою дужкою; тобто, ось так вхідний набір

 complete.<Name of Input Set>
 {
   <List of Substatements>
 }

так вихідний набір

 complete->.<Name of Output Set>
 {
   <List of Substatements>
 }

а так обидва набори

 complete.<Name of Input Set>->.<Name of Output Set>
 {
   <List of Substatements>
 }

Працюватиме й так

 complete(<Number>).<Name of Input Set>->.<Name of Output Set>
 {
   <List of Substatements>
 }

Складена вказівка retro

since v0.7.55

Складена вказівка retro виконує свої підвказівки на дату що вказана в оцінювачі.

Станом на зараз є невизначеність чи вміст змінних ззовні складеної вказівки буде доступний усередині складеної вказівки й подібні нюанси. У майбутніх версіях можуть передаватися лише похідні елементи, середовище — повністю ізолюватися або ж елементи будуть трансформуватися з однієї точки часу в іншу.

Базовий синтаксис такий

retro (<Evaluator>)
{
  <List of Substatements>
}

де <Evaluator> це оцінювач а <List of Substatements> це список підвказівок.

Складена вказівка compare

since v0.7.55

Складена вказівка compare обчислює різницю між даними двох часових міток. Ця різниця може складатися як із будь-яких елементів, так і лише з тих, що мають певні властивості.

Складена вказівка може мати блок підвказівок. Блок підвказівок починає виконуватися після обчислення різниці у другому проході, один раз для старшої часової мітки а потім ще раз для новішої часової мітки. Це дозволяє робити додаткові обчислення на основі результатів різниці.

Складену вказівку можна використовувати лише в режимі різниці. В інших режимах її поведінка невизначена. У майбутніх версіях, можливо, зʼявится повідомлення про синтаксичну помилку, якщо буде спроба виконати її в іншому режимі.

Під час першого запуску запит різниці повертає порожній набір. Під час другого запуску запит різниці повертає різницю елементів. Якщо оператор отримує оцінювач як аргумент, то повертаються лише ті елементи, які мають різні значення у обох часових мітках. Якщо елемент не існує на одній з часових міток, то його значення розглядається як порожній рядок. На даний момент єдиною метою такої різниці є подача її у вихідний набір.

Базовий синтаксис такий:

 compare();

Додатково можна зазначити вхідний та/або вихідний набір:

 .<Set> compare()->.<Set>;

Із оцінювачем синтаксис стає таким:

 compare(delta:<Evaluator>);

Відповідно:

 .<Set> compare->.<Set>(delta:<Evaluator>);

У всіх варіантах синтаксису можна додати блок підвказівок:

 compare()
 {
   <List of Substatements>
 };

Відповідно:

 .<Set> compare(delta:<Evaluator>)->.<Set>;
 {
   <List of Substatements>
 };


Автономні вказівки

out

Вказівка out не повʼязана із глобальним налаштуванням out:. Синтаксис не повинен змішуватись.

Вказівка out подає на вихід вміст набору. Її майже завжди додають до будь-якого запиту Overpass QL.

out count; це вказівка яка виводить лише загальну кількість елементів у вхідному наборі за типом (точки, лінії, звʼязки, полігони). Вона не може бути обʼєднана ні з чим іншим.

Вказівка out у найпростішій формі має кілька типових значень які маються на увазі.

out;         // Вказівка out у найпростішій формі
._ out body; // Ідентична тій що вище

Вхідний набір за замовчуванням _ можна перезаписати якщо додати крапку та назву іменованого набору перед вказівкою out.

.mystuff out; // Подати на вихід набір з назвою «mystuff»

Вказівку out можна налаштувати довільною кількістю параметрів які треба розділити пропусками і вставити між словом out та крапкою з комою у кінці.

Дозволені значення, у будь якому порядку, такі:

  • Одне з цього переліку для рівня докладності вихідних даних; значення за замовчуванням out body:
    • out ids: Виводить лише ідентифікатори елементів у наборі.
    • out skel: Виводить мінімальну кількість геометричної інформації:
      • для точок: ідентифікатор та координати;
      • для ліній: ідентифікатор та ідентифікатори точок з яких утворена лінія;
      • для звʼязків: ідентифікатор звʼязку та ідентифікатори, типи та ролі усіх його членів.
    • out body: Виводить всю інформацію що потрібна для того щоб використовувати дані. Це також теґи для всіх елементів та ролі для членів звʼязків.
    • out tags: Виводить тільки ідентифікатори і теґи для кожного елемента, але не виводить координати чи члени звʼязків.
    • out meta: Виводить усе що відомо про елементи. meta включає усе з чого складається «тіло» кожного елемента OpenStreetMap, включаючи його версію, ідентифікатор набору змін, часову мітку та дані про учасника який востаннє торкнувся обʼєкта. Атрибути метаданих похідних елементів також відсутні для похідних елементів.
Тип самого обʼєкта ID самого обʼєкта Для точок:

їхні власні координати

Для ліній:

ID точок з яких вони утворені

Для звʼязків:

ID, тип, ролі членів

Власні теґи Часова мітка, версія, набір змін, користувач, ID користувача
out ids так так
out skel так так так так так
out body так так так так так так
out tags так так так
out meta так так так так так так так
  • Модифікатор noids дозволяє прибрати із вказівки всі ідентифікатори (Нотатка: Станом на 28 грудня 2021 року, є помилка в Overpass Turbo що не дозволяє використати noids.)
  • Один з модифікаторів інформації з геолокацією з даного переліку; за замовчуванням немає жодного з них:
    • geom: Додає повноцінні дані про геометричну форму для кожного обʼєкта. Він додає координати до кожної точки, то кожної точки що належить лінії чи звʼязку, і також додає послідовність «nd» з координатами для членів всіх звʼязків.
    • bb: Додає лише обмежувальний прямокутник елемента до самого елемента. Для точок це еквівалентно geom. Для ліній це обмежувальний прямокутник що охоплює всі точки з яких створені лінії. Для звʼязків це обмежувальний прямокутник що охоплює всі точки та лінії що є членами таких звʼязків, на члени звʼязків що самі є звʼязками це не впливає.
    • center: Додає лише центр обмежувального прямокутника що мається на увазі для ліній та звʼязків. Нотатка: Центральна точка не обовʼязково знаходитиметься усередині полігону (приклад).
  • Обмежувальний прямокутник у форматі (південь,захід,північ,схід) (зазвичай використовується разом з рівнем докладності geom). У такому випадку будуть продукуватися лише елементи, координати яких знаходяться всередині цього обмежувального прямокутника. Щоб забезпечити коректне формування сегментів ліній, перша та остання координати поза таким обмежувальним прямокутником також будуть додаватися. (Це обмеження не впливає на похідні елементи без будь-якої геометрії).
  • Для порядку сортування можна додати один із модифікаторів нижче:
    • asc: Сортування за ідентифікатором обʼєкта (встановлений за замовчуванням).
    • qt: Сортування за чотирикутним індексом; це менш географічно і набагато швидше ніж порядок за ідентифікаторами (похідні елементи що згенеровані вказівками make чи convert без будь-якої геометрії згрупуються окремо, відсортовані лише за ідентифікатором).
  • Невідʼємне ціле число що обмежує кількість обʼєктів у вихідних даних до максимального зазначеного числа. Якщо модифікатора немає на виході буде увесь набір обʼєктів. Наприклад, out 12; подасть на вихід щонайбільше 12 обʼєктів.

Річ

Автономний запит річ складається тільки з префіксу вхідного набору.

Він бере вхідний набір що зазначений його власним префіксом. Це особливо корисно для вказівок обʼєднання: він відтворює свій вхідний набір як (частину) результату вказівки обʼєднання.

Найпоширенішим є використання із вхідним набором за замовчуванням, _, як показано нижче.

  ._;

Вказівка обʼєднання нижче зʼєднає всі «речі» із вхідного набору із результатом виконання рекурсії вниз яку було застосовано до вхідного набору за замовчуванням. Потім ця вказівка виведе результат назад до того ж самого вхідного набору за замовчуванням і перезапише його.

  (._; >;);

Але, звичайно ж, можна вказувати й інші набори також:

  .a;

А це у контексті вказівки обʼєднання:

  (.a; .a >;);

Нотатка: Вказівка річ не впливає на наступні в черзі підвказівки усередині вказівки обʼєднання. Зокрема, .a; не додає вміст вхідного набору до _, набору «речей» за замовчуванням.

Вказівку річ можна використовувати і як фільтр також.

Рекурсія вгору (<)

Автономний запит рекурсія вгору записується окремим символом, «<».

Він бере вхідний набір. Він продукує підсумковий набір. Цей підсумковий набір утворений з:

  • усіх ліній що мають точку яка зустрілася у вхідному наборі, а також з
  • усіх звʼязків що мають точку або лінію які зустрілися у вхідному наборі, та з
  • усіх звʼязків що мають лінію яка зустрілася у підсумковому наборі.

Приклад:

  <;

Вхідний набір для вказівки рекурсія вгору можна зазначити стандартним префікс-нотуванням:

  .a <;

Підсумковий набір вказівки рекурсія вгору можна перенаправити стандартним постфікс-нотуванням:

  < ->.b;

Звичайно, ви можете змінити обидва записи:

  .a < ->.b;

Рекурсія вгору по звʼязках (<<)

Складена вказівка рекурсія вгору по звʼязках має схожий синтаксис із вказівкою рекурсія вгору, але її зазначають двома символами «менше».

Зокрема, ви можете змінити вхідний та/або підсумковий набір таким самим нотуванням як і для автономного запиту рекурсія вгору.

In addition to the recurse-up results, it continues to follow backlinks onto the found relations until it contains all relations that point to an object in the input or result set.

Precisely, the recurse up relations standalone query returns the transitive and reflexive closure of membership backwards.

Be aware: Done on a node or a way, it will return the parents of that node[1] or way[2] (as expected). Done on a relation, it will return both the relation itself and its parents[3]. If you want the parents only, you can do: (<<; - rel._;); instead[4].

Syntax:

  <<;

Рекурсія вниз (>)

The recurse down standalone query is written as a single greater than.

It takes an input set. It produces a result set. Its result set is composed of:

  • all nodes that are part of a way which appears in the input set; plus
  • all nodes and ways that are members of a relation which appears in the input set; plus
  • all nodes that are part of a way which appears in the result set

In particular, you can change the input and/or result set with the same notation as for the recurse up standalone query.

Example:

  >;

Рекурсія вниз по звʼязках (>>)

The recurse down relations statement has a similar syntax to the recurse down statement, but it is written as a double greater than.

In particular, you can change the input and/or result set with the same notation as for the recurse-down standalone query.

It continues to follow the membership links including nodes in ways until for every object in its input or result set all the members of that object are in the result set as well.

Precisely, the recurse down relations statement returns the transitive and reflexive closure of membership.

Syntax:

  >>;

Запит на полігони (is_in)

The standalone query is_in returns the areas and closed ways that cover

  • the given coordinates (when specified) or
  • one or more nodes from the input set (when no coordinates are specified).

It takes either an input set or a coordinate and produces a result set. The results are all areas which contain at least one of the nodes from the input set or the specified coordinate.

is_in cannot be directly used with any of the Overpass QL filters. For filtering the is_in result, a further query is needed (see below): the [square brackets] shown below, indicate optional parts and are not part of the syntax to type.

  [.input_set] is_in         [-> .result_set];
  is_in(latitude, longitude) [-> .result_set];

In its shortest form, it takes its input set as the locations to search for. Example:

  is_in;

The input set can be chosen with the usual prefix notation:

  .a is_in;

The result set can be redirected with the usual postfix notation:

  is_in->.b;

Of course, you can also change both:

  .a is_in->.b;

Instead of taking existing nodes you can also specify coordinates with two floating point numbers, divided by a comma. They are interpreted as latitude, longitude. In this case, the input set is ignored. Example:

  is_in(50.7,7.2);

Also in this variant, the result set can be redirected with the usual postfix notation:

  is_in(50.7,7.2)->.b;

Area creation depends on some specific extraction rules, there's no area counterpart for each and every OSM relation! For more details see areas.osm3s and the Areas Wiki page.

To filter the result returned by is_in by additional filter criteria, an additional query is needed:

  is_in(48.856089,2.29789);
  area._[admin_level="2"];     // ._ represents the default inputset, which contains all areas returned by ''is_in''

Вказівка хронології timeline

since v0.7.55

The statement timeline takes type and id of an object and optionally version as arguments. It then returns a derived structure containing the meta information of the specified version. If no version is specified then one object for each known version is returned. Each of these objects has tags ref, reftype, and refversion to identify the reference. In addition, it has tags created and expired that contain the relevant timestamps.

The base syntax is

 timeline(<Type>, <Ref>);

resp.

 timeline(<Type>, <Ref>, <Version>);

where <Type> is one of the three literals node, way, or relation.

In addition, an output set <Set> can be specified:

 timeline(<Type>, <Ref>)->.<Set>;

resp.

 timeline(<Type>, <Ref>, <Version>)->.<Set>;


Вказівка local

since v0.7.55

The statement local converts the given input into the localized representation of OSM data. The output parameter controls which classes of data are included.

Without a type parameter local delivers geometry and tags. This is one object per tagged node plus one object per part of a way plus one object per part of a relation geometry.

With the type parameter "ll", it delivers additionally loose objects. There are one object per way with tags but without node members and one object per relation member of any relation without node or way members.

With the type parameter "llb", it delivers even more data: It delivers the objects that associate the OSM element ids to the aforementioned objects.

The base syntax is

 local <Type>

where <Type> is empty, "ll", or "llb". You can also specify other input and/or output sets than "_":

 .<Set> local <Type> ->.<Set>

The first set is the input set, the second set is the output set.

Вказівка convert

since v0.7.54

The statement convert produces one output element for every element in its input set. Its input and output sets are always the default set.

The content of each output element is controlled by the parameters of the statement. The statement discards geometry (lat/lon info).

The base syntax is

 convert <Type> <List of Tags>

where <List of Tags> is a comma separated list of items, each of which must be one the following

 <Key> = <Evaluator>
 ::id = <Evaluator>
 :: = <Evaluator>
 !<Key>

The first parameter, <Type>, must have a fixed value. <Type> must start with a letter, and every following character can be either an alphanumeric character or an "_". <Type> controls the type of each output element.

The following parameters are used to set an arbitrary number of tags on each output element.

In the below description, each <Evaluator> is evaluated with an input element in context (see Overpass API/Overpass QL#Element Dependent Operators).

For each element in the input set:

  • <Key> = <Evaluator> adds a key to the corresponding output element with value <Evaluator> evaluated with key <Key> (relevant for the generic evaluator).
  • ::id = <Evaluator> sets the id of the corresponding output element to the value of <Evaluator>
  • :: = <Evaluator> is equivalent to <Key> = <Evaluator> for every key in the input element. This is called the generic key mechanism.
  • !<Key> prevents key <Key> from being set in the output element by the generic key mechanism.

Keys set explicitly with the <Key> = <Evaluator> syntax override keys set with the generic key mechanism.

If you do not set an id then a unique id from a global ascending counter is assigned.

It is a syntax error to set the same key twice using the <Key>=<Evaluator> or !<Key> items.

Вказівка make

since v0.7.54

The statement make produces a set containing a single output element. Its output set is always the default set. The statement has no input set.

The content of the output element is controlled by the parameters of the statement. The statement cannot produce geometry (lat/lon info) on its output element.

The base syntax is

 make <Type> <List of Tags>

where <List of Tags> is a comma separated list of items, each of which must be one the following

 <Key> = <Evaluator>
 ::id = <Evaluator>
 <Set>:: = <Evaluator>
 !<Key>

Note the difference from the convert statement syntax. In the make statement, the generic key mechanism requires an explicit input set.

The first parameter, <Type>, must have a fixed value. <Type> must start with a letter, then can contain alphanumeric characters and "_". <Type> controls the type of each output element.

The following parameters are used to set an arbitrary number of tags on the output element.

A description of each parameter item is below. Note that unlike in a convert statement, there is no element in context for the evaluators, so element dependent operators cannot be used.

  • <Key> = <Evaluator> adds a key to the output element with value <Evaluator> evaluated with key <Key> (relevant for the generic evaluator).
  • ::id = <Evaluator> sets the id of the output element to the value of <Evaluator>
  • <Set>:: = <Evaluator> is equivalent to <Key> = <Evaluator> for every key that appears at least once in an element in <Set>. This item is called the generic key mechanism.
  • !<Key> prevents key <Key> from being set in the output element by the generic key mechanism.

Keys set explicitly with the <Key> = <Evaluator> syntax override keys set with the generic key mechanism.

If you do not set an id then a unique id from a global ascending counter is assigned.

It is a syntax error to set the same key twice using the <Key>=<Evaluator> or !<Key> items. Also, at most one generic key can be set.

Питальна вказівка

Найважливішою вказівкою є питальна вказівка. Це не одна окрема вказівка а швидше така що складається з одного з типів специфікаторів node, way, relation (або скорочено rel), derived, area, або nwr (скорочення для «точки, лінії або звʼязки) за якими йдуть один або більше фільтрів. Підсумковий набір це набір з усіма елементами що відповідають на умови, зазначені у всіх фільтрах.

Приклад:

// один фільтр
  node[name="Foo"];
  way[name="Foo"];
  rel[name="Foo"];
  nwr[name="Foo"];
  nw[name="Foo"];
  nr[name="Foo"];
  wr[name="Foo"];
  derived[name="Foo"];
  area[name="Foo"];

// кілька фільтрів
  node[name="Foo"][type="Bar"];

Here, node, way, rel, nwr, derived, and area are the type specifier, [name="Foo"] resp. [type="Bar"] is the filter and the semicolon ends the statement.

The query statement has a result set that can be changed with the usual postfix notation.

  node[name="Foo"]->.a;

The individual filters may have in addition input sets that can be changed in the individual filters. Please see for this at the respective filter.

The Query Filter

The query filter can be added as condition to a query statement. It has an evaluator as argument and it lets pass only those elements for which the expression returns boolean true.

At the moment, the query filter cannot be the only condition in a query. This is due to implementation reasons and will change in future versions.

It is technically possible to have multiple query filters in a single query. But it does not make sense: Their evaluators can be combined with a conjunction in a single query filter. This has the same semantics and is faster.

Its syntax is

 (if: <Evaluator>)

The whitespace is optional.

Фільтри

За теґом (has-kv)

The has-kv filter selects all elements that have or have not a tag with a certain value. It supports the basic OSM types node, way, and relation as well as the extended type area.

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

All variants consist of an opening bracket, then a string literal in single or double quotes. Then the variants differ. All variants end with a closing bracket. If the string literal consists only of letters, the quotes can be omitted.

Рівність (=, !=)

The most common variant selects all elements where the tag with the given key has a specific value. This variant contains after the key literal an equal sign and a further literal containing the value. Examples, all equivalent:

  node[name=Foo];
  node[name='Foo'];
  node[name="Foo"];
  node['name'="Foo"];
  node["name"="Foo"];
  node["name"='Foo'];

If you have a digit, whitespace or whatever in the value, you do need single or double quotes:

  node[name="Foo Street"];
  node["name:fr"="Rue Feau"];

Querying for empty values is not possible using the equals value operator. This can only be achieved by using a regular expression:

node[power=""];          // not supported
node[power~"^$"];        // use regular expression instead

Likewise, querying empty key values is also not possible using this kind of key-value query and needs to be expressed via regular expressions.

node[~"^$"~"."];         // find nodes with empty key ("") and any value

NB: Overpass Turbo Wizard already has some logic in place to automatically convert ""="" accordingly.

Наявність

The second variant selects all elements that have a tag with a certain key and an arbitrary value. It contains nothing between the key literal and the closing bracket:

  node["name"];
  node['name'];
  node[name];

Ненаявність

since v0.7.53

This variant selects all element, that don't have a tag with a certain key and an arbitrary value.

  node[!"name"];
  node[!'name'];
  node[!name];

In previous versions, 'not exists' had to be written as node["name"!~".*"];.

Значення що збігається з регулярним виразом (~, !~)

The third variant selects all elements that have a tag with a certain key and a value that matches some regular expression. It contains after the key literal a tilde, then a second literal for the regular expression to search for:

Statement Explanation
node["name"~"^Foo$"]; Finds nodes, where the tag name matches exactly Foo - identical to node["name"="foo"];
node["name"~"^Foo"]; Finds nodes, where the tag name starts with Foo
node["name"~"Foo$"]; Finds nodes, where the tag name ends with Foo
node["name"~"Foo"]; Finds nodes, where the tag name contains the substring Foo anywhere in the tag value
node["name"~".*"]; Finds nodes, where the tag name matches anything, equal to node["name"];
node["name"!~".*"]; Finds nodes without name tag; does not have key name - identical to node[!"name"];

Please note that in QL you need to escape backslashes: ["name"~"^St\."] results in the regular expression ^St. (which finds every name starting with "St"), while ["name"~"^St\\."] produces the most likely meant regular expression St\. (which finds every name starting with "St."). This is due to the C escaping rules and doesn't apply to the XML syntax.

Overpass implements the POSIX Extended regular expression syntax.

Нечутливість до регістру літер

You can also search case insensitively

  node["name"~"^Foo$",i];    /* finds "foo", "FOO", "fOo", "Foo" etc. */

Both the key and value variants with and without regular expressions can be negated. They then select exactly the elements which have a tag with the given key, but no matching value and the elements that don't have a tag with the given key:

  node["name"!="Foo"];
  node["name"!~"Foo"];
  node["name"!~"Foo",i];

Ключ чи значення що збігається з регулярним виразом (~"key regex"~"value regex")

The fourth variant selects all elements where both key and value match a regular expression. After an initial tilde (~) the regular expression for the key needs to be provided, followed by another tilde character and eventually the regular expression for the value.

  node[~"^addr:.*$"~"^Foo$"];    /* finds addr:* tags with value exactly "Foo" */
  node[~"^addr:.*$"~"^Foo"];     /* finds addr:* tags with value starting with "Foo" */
  node[~"^addr:.*$"~"Foo$"];     /* finds addr:* tags with value ending with "Foo" */
  node[~"^addr:.*$"~"Foo"];      /* finds addr:* tags with value containing the substring "Foo" */
  node[~"^addr:.*$"~"."];        /* finds addr:* tags with any value */
  node[~"^name(:.*)?$"~"."];     /* finds anything with a name or name:lang tag, and with any value */
  node[~"^name(:ar|:he)?$"~"."]; /* finds anything with name, name:ar, or name:he tag, and with any value*/

This format also supports case-insensitive searches: node[~"^addr:.*$"~"^Foo$",i];. Case-insensitivity applies to both tag key and value searches in this case.

Обмежувальний прямокутник

Фільтр запиту обмежувальний прямокутник обирає всі елементи що знаходяться всередині обмежувального прямокутника.

Він не має вхідного набору. Так як і всі фільтри, підсумковий набір визначається усією вказівкою загалом а не окремим фільтром.

  (південь,захід,північ,схід)

Фільтр починається з відкритої дужки, потім записуються чотири числа у вигляді десяткових дробів, розділені комами. Фільтр закінчується закритою дужкою.

Десяткові дроби показують межі обмежувальної коробки: перше число — південну межу або мінімальну широту. Друге — західну межу, зазвичай, мінімальну довготу. Третє — північну межу або максимальну широту. Останнє число — це східна межа, зазвичай, максимальна довгота. Якщо друге числове значення більше за четверте значення, обмежувальний прямокутник перетинає 180-градусну довготу.

Приклад:

  node(50.6,7.0,50.8,7.3);

Прочитайте також про #глобальний обмежувальний прямокутник.

Рекурсія (n, w, r, bn, bw, br)

The recurse filter selects all elements that are members of an element from the input set or have an element of the input set as member, depending on the given parameter.

The input set can be changed with an adapted prefix notation. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows one of the symbols: w (forward from ways), r (forward from relations), bn (backward from nodes), bw (backward from ways), or br (backward from relations). Then follows an optional input set declaration. The filter ends with a closing parenthesis.

Examples with default input set:

  node(w);            // select child nodes from ways in the input set
  node(r);            // select node members of relations in the input set
  way(bn);            // select parent ways for nodes in the input set
  way(r);             // select way members of relations in the input set
  rel(bn);            // select relations that have node members in the input set
  rel(bw);            // select relations that have way members in the input set
  rel(r);             // select relation members of relations in the input set
  rel(br);            // select parent relations from relations in the input set

Example with modified input set:

  node(w.foo);        // select child nodes from ways in the "foo" input set

You can also restrict the recurse to a specific role. Just add a colon and then the name of the role before the closing parenthesis.

Examples with default input set:

  node(r:"role");     // select node members of relations in the input set
  way(r:"role");      // select way members of relations in the input set
  rel(bn:"role");     // select relations that have node members in the input set
  rel(bw:"role");     // select relations that have way members in the input set
  rel(r:"role");      // select relation members of relations in the input set
  rel(br:"role");     // select parent relations from relations in the input set

Example with modified input set:

  node(r.foo:"role"); // select node members with role "role" of relations in the "foo" input set

And you can also search explicitly for empty roles:

  node(r:"");         // select node members with empty role of relations in the input set
  node(r.foo:"");     // select node members with empty role of relations in the "foo" input set

Рекурсія (way_cnt, way_link)

These variants of recurse select all nodes that are member of a specific number of way resp. way segments. Both need a number or a range as second argument and optinally can have an input set.

The way_cnt criterion selects those nodes that are members of a given number of ways. E.g. the criterion (way_cnt:2) selects all crossings between ways and all nodes where two ways join.

By contrast, the way_link criterion counts way segments. Inner nodes without a crossing have way link count two, because there is exactly one segment to connect to the predecessor and one segment to connect to the successor. Joins also have segment count two. This is way it is easy to select independently crossings bceause they have segment count three or greater or dead ends because they have segment count one.

Examples with default input set:

  node(way_cnt:2);    // select those nodes that are members of exactly two of the given ways
  node(way_cnt:3-4);  // select those nodes that are members of three to four of the given ways
  node(way_cnt:2-);   // select those nodes that are members of two or more of the given ways
  node(way_link:1);    // select those nodes that are members of exactly one segment of the given ways, i.e. are dead ends
  node(way_link:4-5);  // select those nodes that are members of four to five segments of the given ways
  node(way_link:3-);   // select those nodes that are members of three or more segments of the given ways, i.e. crossings

Example with modified input set:

  node(way_link.foo:3-);   // select those crossing nodes based on the way grid in set foo

За вхідним набором (.setname)

Фільтр «річ» вибирає всі елементи з вхідного набору.

Так як і для всіх фільтрів, підсумковий набір визначається усією вказівкою, а не окремим фільтром.

Він починається з точки, за якою йде назва вхідного набору.

Приклади: Набір за замовчуванням:

  node._;

та іменований набір:

  node.a;

Також можливо вказати кілька вхідних наборів (перетин наборів). Наприклад:

  node.a.b;
Такий набір видасть усі точки які є у обох наборах одночасно: і у вхідному наборі .a і у вхідному наборі .b.

За ідентифікатором елемента

The id-query filter selects the element of given type with given id. It supports beside the OSM datatypes node, way, and relation also the type area.

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows a positive integer. The filter is ended with a closing parenthesis.

Examples:

  node(1);
  way(1);
  rel(1);
  area(1);

Area ids are derived from an existing OSM way by adding 2400000000 to its OSM id or in case of a relation by adding 3600000000. Note: Due to the large OSM data growth, these values might have to be changed in 2022 or 2023 to avoid overlapping values (!) You should use the map_to_area function to avoid having to make these calculations manually and depend on any hard-coded constants in your query.

Area creation is subject to some extraction rules, i.e. not all ways/relations have an area counterpart. See areas.osm3s for details.

Since version 0.7.54, the id-query filter also supports multiple values. To avoid conflicts with the bounding box filter, a new mandatory id: prefix has to be used in this case.

   node(id:1000,1001,1002,1003,1004,1005);
   way(id:3998029,3998240,4065354,4065364,4065392,4065421);
   rel(id:10815,10816);
   area(id:1234);

Performance hint: Try to bundle multiple id queries into one statement, i.e. instead of writing (way(3998029);way(3998240);way(4065354);); use way(id:3998029,3998240,4065354);

Відносно інших елементів (навколо)

The around filter selects all elements within a certain radius in metres around the elements in the input set. If you provide coordinates, then these coordinates are used instead of the input set. The input set can be changed with an adapted prefix notation. As for all filters, the result set is specified by the whole statement, not the individual filter.

A radius of 0 can be used for a way intersection test on outer/inner points.

Syntax: It consists of an opening parenthesis. Then follows the keyword around. Then follows optionally an input set declaration. Then follows a single floating point number that denotes the radius in meters. The filter either ends with a closing parenthesis or is followed by two comma separated floating point numbers indicating latitude and longitude and then finally a closing parenthesis.

  (around[.input_set]:radius)
  (around:radius,latitude,longitude)

Since version 0.7.55, it is possible to query for all elements which are within a certain radius of a given linestring, which is given by a list of lat/lon pairs:

  (around[.input_set]:radius)
  (around:radius,latitude_1,longitude_1,latitude_2,longitude_2,...,latitude_n,longitude_n)

Example:

  node(around:100.0);
  way(around:100.0);
  rel(around:100.0);

Example with modified input set:

  node(around.a:100.0);

Example with coordinates:

  node(around:100.0,50.7,7.1);
  way(around:100.0,50.7,7.1);
  rel(around:100.0,50.7,7.1);

Example with linestring:

try it yourself in overpass-turbo
way[highway](around:500,50.540853270068986,8.048780365649707,50.53106288705902,8.030823236553783,50.51780737956311,8.019643105996508,50.50287491071276,8.016749912560886,50.48828159051387,8.022534398052139,50.47599950382573,8.036215335651725,50.467689755650376,8.055945038928135,50.46447690759688,8.079058902127825,50.46679590711731,8.102435269947343,50.47433280529453,8.122917034379736,50.48606755168466,8.137738019645033,50.50041288059356,8.144896569557243,50.51542994506574,8.143425882283827,50.529090915610794,8.13352458229042,50.53955268865336,8.11652989500613,50.545404823255616,8.09473704711951,50.545858734919165,8.07108928349599,50.540853270068986,8.048780365649707)   
;(._;>;);out meta;

For further use cases, see this diary entry.

Example: Find all cinema nodes in Bonn which are at most 100m away from bus stops

try it yourself in overpass-turbo
area[name="Bonn"];
node(area)[highway=bus_stop];
node(around:100)[amenity=cinema];
out;

Find both cinema nodes and ways in Bonn, which are at most 100m away from bus stop nodes:

try it yourself in overpass-turbo
area[name="Bonn"];
node(area)[highway=bus_stop]->.bus_stops;
( 
  way(around.bus_stops:100)[amenity=cinema];
  node(around.bus_stops:100)[amenity=cinema];
);
(._;>;);
out meta;

За полігоном (poly)

The polygon filter selects all elements of the chosen type inside the given polygon.

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows the keyword poly. Then follows a string containing an even number of floating point numbers, divided only by whitespace. Each pair of floating point numbers represents a coordinate, in order latitude, then longitude. The filter ends with a closing parenthesis:

  (poly:"latitude_1 longitude_1 latitude_2 longitude_2 latitude_3 longitude_3 …");

An example (a triangle near Bonn, Germany):

  node(poly:"50.7 7.1 50.7 7.2 50.75 7.15");
  way(poly:"50.7 7.1 50.7 7.2 50.75 7.15");
  rel(poly:"50.7 7.1 50.7 7.2 50.75 7.15");

Performance hint: A large number of latitude/longitude pairs slows down the (poly: ) filter, hence simplifying the polyline geometry before using it in a poly filter is recommended.

newer

The newer filter selects all elements that have been changed since the given date. As opposed to other filters, this filter cannot be used alone. If the underlying database instance supports attic data and the date difference is at most one month, then "changed" is probably a better choice than "newer".

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows a date specification. Please note that this date specification cannot be abbreviated and has to be put in single or double quotes. The filter ends with a closing parenthesis.

Example:

  node._(newer:"2012-09-14T07:00:00Z");
This finds all nodes that have changed since 14 Sep 2012, 7 h UTC, in the given input set.

За датою змінення (changed)

The changed filter selects all elements that have been changed between the two given dates. If only one date is given, then the second is assumed to be the front date of the database. If only one date is given and it is run with the current timestamp, then it behaves exactly like "newer" with two exceptions: first, it is faster (see note), second, it can also stand as the only filter.

Note: As of June 2017, a known bug can cause "changed" to be much slower than "newer" in some cases. Consider using "newer" until it is resolved, or consider testing which one runs faster for you. See the following Github issues: #278 (resolved), #322, #346. See this discussion too.

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows a date specification. Please note that this date specification cannot be abbreviated and has to be put in single or double quotes. Then can follow a comma and a second date specification. The filter ends with a closing parenthesis.

Example: All changes since the given date and now

  node._(changed:"2012-09-14T07:00:00Z");

Example: All changes between the two given dates

  node._(changed:"2012-09-14T07:00:00Z","2012-09-14T07:01:00Z");

За іменем чи ідентифікатором учасника (user, uid)

The user filter selects all elements that have been last touched by the specified user.

It has no input set. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows either the keyword user, a colon and a string literal denoting the user name to search for. Or the keyword uid followed by the user id of the user to search for. The filter ends with a closing parenthesis.

Example:

  node(user:"Steve");
  node(uid:1);

Since release 0.7.53 it is also possible to specify multiple user names:

  node(user:"Mapper1","Mapper2","Mapper 3");
  node(uid:1,2,4,8,16);

By area (area)

The area filter selects all elements of the chosen type that are inside the given area or areas. Please note with regard to attic data that areas derived from relations always represent current data.

The input set can be changed with an adapted prefix notation. As for all filters, the result set is specified by the whole statement, not the individual filter.

Syntax: It consists of an opening parenthesis. Then follows the keyword area. Then can follow a colon and a non-negative integer. The filter ends with a closing parenthesis.

Nodes are found if they are properly inside or on the border of the area. Ways are found if at least one point (also points on the segment) is properly inside the area. A way ending on the border and not otherwise crossing the area is not found. Relations are found if one of its members is properly inside the area.

If the area statement is provided without integer, the areas from the input set are used. An example:

  node(area);
  way(area);
  rel(area);

The example with modified input set:

  node(area.a);
  way(area.a);
  rel(area.a);

If an integer is added, the input set is ignored and instead the area that has the given integer as id is taken. For example:

// NOTE: 2400xxx AREA IDS FOR WAYS ARE NO LONGER SUPPORTED SINCE RELEASE 0.7.57

  node(area:2400000001);       
  way(area:2400000001);
  rel(area:2400000001);

Caveat: area(area); is currently not supported. In this case, the (area) filter will be silently ignored, leading to unexpected results.

Because areas in OSM are not native elements but are only inferred from the OSM database using its closed ways or relations; this facility allows grouping their various representation in a coherent set which can store their geometry, independently of their complexity and representation in the OSM database, as if they were a single distinctive element, without using complex filtering rules in your query. However associating these objects with an OSM id attribute requires some adjustment because the same id value could be used for unrelated elements with different type (way or relation). For this reason, areas returned by the Overpass API only have a "virtual" id specific to the Overpass API, but not found directly in the OSM database.

By convention the area id can be calculated from an existing OSM relation by adding 3600000000 respectively. Note that area creation is subject to some extraction rules, i.e. not all relations have an area counterpart (notably those that are tagged with area=no, and most multipolygons and that don't have a defined name=* will not be part of areas).

Areas are created by a regular job on the Overpass API server and usually have a lag of several hours compared to the OSM main database. The exact timestamp can be determined by checking the `timestamp_areas_base` value in the Overpass json or xml result.

If you want more immediate results (not depending on the delayed batch processing), you can also write your own filters without using this facility in your Overpass query: use standard OSM element types and ids and filter them by specific tags of your choice.

See areas.osm3s for details of the filters (written using the XML variant of the Overpass query language) currently by Overpass used to generate the areas that can be queried with this facility. Those areas are defined using the "pivot" query feature (see below).

Area pivot (pivot)

The pivot filter selects the element of the chosen type that defines the outline of the given area.

The input set can be changed with an adapted prefix notation. As for all filters, the result set is specified by the whole statement, not the individual filter.

It consists of an opening parenthesis. Then follows the keyword pivot. The filter ends with a closing parenthesis.

The statement finds for each area in the input set the respective element that the area has been generated from. Derived areas are derived from relations. Closed way represent themselves and are therefore passed from the input set to the output set.

Examples:

// These use the default input set '_'
way(pivot);
rel(pivot);
// These use the input set 'a'
way(pivot.a);
rel(pivot.a);

The following example determines the area(s) for the county of Greater London, and stores the result in the set londonarea. In the next statement, the areas contained in the londonarea set are converted back into their corresponding OSM relations using the pivot filter. Finally, out geom; outputs the relations (including their child ways and nodes).

area[name="London"][admin_level=6][boundary=administrative]->.londonarea;
rel(pivot.londonarea);
out geom;

Conditional query filter (if:)

since v0.7.54

The query filter can be added as condition to a query statement. It has an evaluator as argument and it lets pass only those elements for which the expression returns boolean true.

At the moment, the query filter cannot be the only condition in a query. This is due to implementation reasons and will change in future versions.

It is technically possible to have multiple query filters in a single query. But it does not make sense:

  • Their evaluators can be combined with a conjunction in a single query filter.
  • This has the same semantics and is faster.

Its syntax is:

 (if: <Evaluator>)

The whitespace is optional.

Many filters above can be generalized using conditional query filter, if one needs more specific conditions for filter the objects in the query input set. For example, the query:

  node[name=foo];

is equivalent to the following one using a conditional query filter (but for simplicity the former syntax using simpler a filter by tag value is still recommended, as it may have better performance on the Overpass server, and because the new syntax for evaluators may still not be supported in the current implementation of Overpass servers and client libraries before version 0.7.54 of the API):

  node(if: t["name"] == "foo");


Оцінювачі

Evaluators are building blocks that yield on execution a value. The use of which of the evaluators makes sense depends on the context.

Evaluators help to filter for elements within a query statement. They allow to get statistical information about query results. And they allow to remove or add tags from elements.

Currently only tag evaluators are supported. Geometry evaluators are planned but not implemented in this version.

The following types of evaluators exist and are explained further down:

  • Const evaluators deliver always the same value independent of context.
  • Element dependent evaluators deliver information about an individual object.

They only make sense in the context of a single element.

  • Statistical evaluators deliver information about a set as a whole.
  • Aggregators let an element dependent evaluator loop over all elements of a set and combine its results.
  • Operators and endomorphisms combine the result of one or two evaluator executions into a new result.

TODO:

  • Need to add simple examples for each section, similar to e.g. regular expressions before.
  • Merge some of the very simple explanations in the blog posts back into this document.

Literals

Literals represent fixed values, and can be used for comparisons and tests against operators, and as arguments to evaluators. Examples of literals:

Literal Explanation
3 The whole number value 3 †*
3.14159 The floating point number 3.14159 †*
2017-09-28T19:51:44Z An ISO 8601 timestamp, in the format in common use in the OpenStreetMap database.

The format is YYYY-MM-DDThh:mm:ssZ. ‡

London Bridge A string of characters ‡
addr:housenumber A string representing a commonly used OpenStreetMap key, addr:housenumber

† Integers and floating point numbers treated as numbers and expressed as less than zero (e.g -1.3) are not themselves literals. They are literals modified with the unary minus operator.

* Some positive and negative integer and floating point numbers, (such as when used in the context of the bounding box query filter), are interpreted as strings.

‡ It is generally wise to include quotes around these literals, to avoid the possibility of characters like : - or whitespace being incorrectly interpreted by an evaluator. For example, "London Bridge" and "addr:housenumber" avoids parsing issues inside tag evaluators. "2017-09-28T19:51:44Z" is a safe way to write a timestamp literal.

Some functions, such as date(), will attempt to type cast a literal into a standard format suitable for Overpass QL.


Fixed Value evaluator

This operator always returns a fixed value. It does not take any argument.

Its syntax is

 <Value>

Element Dependent Operators

Element dependent operators depend on one or no parameter. Their syntax varies, but most have the appearance of a function name plus parentheses.

They can only be called in a context where elements are processed. This applies to convert, to filter, or to arguments of aggregate functions. They cannot be called directly from make.

Id and Type of the Element

The operator id returns the id of the element. The operator type returns the type of the element. Both operators take no parameters.

The syntax is

 id()

resp.

 type()

Tag Value and Generic Value Operators

The tag operator returns the value of the tag of the given key. The is_tag operator returns "1" if the given element has a tag with this key and "0" otherwise. They only can be called in the context of an element.

Their syntax is

 t[<Key name>]

resp.

 is_tag(<Key name >)

The <Key name> must be in quotation marks if it contains special characters.

The tag operator can also be called with a substatement. Its syntax is then

 t[<Substatement>]

The generic tag operator returns the value of the tag of the key it is called for. It only can be called in the context of an element. In addition, it must be part of the value of a generic property to have its key specified.

Its syntax is

 ::

All Keys Evaluator

The all keys evaluator returns a container of the keys of the given element.

Its syntax is

 keys()


Meta Data Operators

The version operator returns the version number of the given element. Its syntax is:

 version()

The timestamp operator returns the timestamp of the given element. Its syntax is:

 timestamp()

The changeset operator returns the changeset id of the changeset in which the given element has been last edited. Its syntax is:

 changeset()

The uid operator returns the id of the user that has last touched the given element. Its syntax is:

 uid()

The user operator returns the name of the user that has last touched the given element. Its syntax is:

 user()

Element Properties Count

since v0.7.55

This variant of the count operator counts tags or members of the given element. Opposed to the statistical variant of the count operator, they cannot take an input set as extra argument.

The syntax for tags is

 count_tags()

The syntax to count the number of member entries is

 count_members()

The syntax to count the number of distinct members is

 count_distinct_members()

The syntax to count the number of member entries with a specific role is

 count_by_role()

The syntax to count the number of distinct members with a specific role is

 count_distinct_by_role()

Per Member Aggregators

Aggregators per member help to process information that does apply to only a single member of a way or relation. Examples of this are the position within the way or relation, geometric properties like the angles, or roles. A per member aggregator needs an element to operate on and executes its argument multiple times, passing the possible positions one by one in addition to the element to its argument.

Per Member

since v0.7.56

For each element, the aggregator executes its argument once per member of the element. The return value is a semicolon separated list of the return values. No deduplication or sorting takes place. Note that the aggregator returns an empty value for nodes and deriveds and does not execute its argument in that case.

The syntax is

 per_member(<Evaluator>)

Per Vertex

since v0.7.56

For each element, the aggregator executes its argument once per (inner) vertex of the element. Otherwise it behaves similar to the per_member operator. For closed ways, this means that it is executed once for all vertices but the first member. For open ways, it is executed once for all vertices but the first and last member. For relations its behaviour is currently undefined.

The syntax is

 per_vertex(<Evaluator>)

Member Dependent Functions

Member dependent functions can only be used when an element plus a position within the element is in context. They then deliver specific information for that member.

Position of the Member

since v0.7.56

The position function returns for a member its one-based position within the element.

The syntax is

 pos()

Reference to the Member

since v0.7.56

The functions mtype and reference return for a member the type resp. id of the referenced object.

The syntax is

 mtype()

resp.

 ref()

Role of the Member

since v0.7.56

The role function returns the role of the member.

The syntax is

 role()

Angle of a Way at the Position of a Member

since v0.7.56

This function returns the angle between the segment ending at this member and the segment starting there. It is so far only defined for ways. If the way is a closed way then for the last member the first segment is used as the starting segment. This function is intended to be used within the per_vertex() enumerator.

The syntax is

 angle()

Geometry Related Operators

Closedness

since v0.7.55

The operator is_closed returns whether the element is a closed way. The operator is undefined for any other type of element. For ways, it returns "1" if the first member of the way is equal to the last member of the way and "0" otherwise. The operators takes no parameters.

The syntax is

 is_closed()

Example: Find all Danish roundabouts that are not closed circles

area["ISO3166-1"="DK"][admin_level=2];
way["junction" = "roundabout"](area)
  (if: is_closed() == 0);

Geometry

since v0.7.55

The geometry operator returns the geometry of a single object as a geometry that can be put into the other geometry converting operators.

Its syntax is:

 geom()

Length

since v0.7.55

The length operator returns the length of the element in meters. For ways this is the length of the way. For relations this is the sum of the lengthes of the members of type way. For nodes it is always zero.

Its syntax is:

 length()

Latitude and Longitude

since v0.7.56

The latitude and longitude operators return the respective coordinate of the element or the element's center. For nodes it is the latitude resp. longitude of the node's coordinate. For ways and relations it refers to the coordinate derived from the center of the bounding box.

Their syntaxes are:

 lat()

resp.

 lon()

Point evaluator

since v0.7.55

The point evaluator, syntax pt(<latitude>, <longitude>), returns a valid OpenStreetMap node geometry. The geometry returned is a node at the latitude and longitude derived from the two given values. Each user supplied value, latitude and longitude, should parse as a valid floating point number.

  • latitude must fall within the range of -90 to 90, inclusive. Digits beyond 10e-7 (which is beyond the accuracy OpenStreetMap saves a node in) are ignored if within this range.
  • longitude must fall within the range of -180 to 180, inclusive. Digits beyond 10e-7 (which is beyond the accuracy OpenStreetMap saves a node in) are ignored if within this range.

Linestring evaluator

since v0.7.55

This operator always returns a geometry. The geometry is a line made of the points that are supplied as arguments.

Its syntax is

 lstr(<Evaluator>, <Evaluator>[, ...])


Polygon evaluator

since v0.7.55

This operator always returns a geometry. The geometry is a polygon made of the linestrings that are supplied as arguments. The polygon adheres to the right hand rule and has no self-intersections.

Its syntax is

 poly(<Evaluator>, <Evaluator>[, ...])

Aggregators

Aggregators need for execution both a set to operate on and an evaluator as argument. That evaluator will loop over each element of the set, and the aggregator will combine its results.

Union and Set

These two aggregation functions execute their evaluators on each element of a specified set, returning a text value. The basic syntax is:

 <Set>.u(<Evaluator>)
 <Set>.set(<Evaluator>)

For the default set _ the set parameter can be left off:

 u(<Evaluator>)
 set(<Evaluator>)

set returns a semi-colon separated list of all distinct values that appear.

u is meant to operate on sets returning a single unique value such as sets with only one member. If only one value is found, then that value is returned. If no value is found then u returns an empty string. If multiple different values are found then u returns the text "< multiple values found >".

Min and Max

The basic syntax is

 <Set>.min(<Evaluator>)

resp.

 <Set>.max(<Evaluator>)

If the set is the default set _ then you can drop the set parameter:

 min(<Evaluator>)

resp.

 max(<Evaluator>)

These two evaluators execute their right hand side evaluators on each element of the specified set. If all return values are valid numbers then min returns the minimal amongst the numbers. Likewise, if all return values are valid numbers then max returns the maximal amongst the numbers. If not all return values are valid numbers then min returns the lexicographically first string. Likewise, if not all return values are valid numbers then max returns the lexicographically last string. If no value is found then each min and max return an empty string.

Sum

The basic syntax is

 <Set>.sum(<Evaluator>)

If the set is the default set _ then you can drop the set parameter:

 sum(<Evaluator>)

This evaluator executes its right hand side evaluators on each element of the specified set. If all return values are valid numbers then sum returns their sum. If not all return values are valid numbers then sum returns "NaN".

Statistical Count

This variant of the count operator counts elements of a given type in a set.

The syntax variants

 count(nodes)
 count(ways)
 count(relations)
 count(deriveds)
 count(nwr)
 count(nw)
 count(wr)
 count(nr)

counts elements in the default set _, and the syntax variant

 <Set>.count(nodes)
 <Set>.count(ways)
 <Set>.count(relations)
 <Set>.count(deriveds)
 <Set>.count(nwr)
 <Set>.count(nw)
 <Set>.count(wr)
 <Set>.count(nr)

counts elements in the set <Set>.

Union of Geometry

since v0.7.55

The basic syntax is

 <Set>.gcat(<Evaluator>)

If the set is the default set _ then you can drop the set parameter:

 gcat(<Evaluator>)

The evaluator executes its right hand side evaluator on each element of the specified set. It then combines the obtained geometries in one large object. If geometries are contained multiple times in the group then they are as well repeated as members of the result.

Unary Operators

Unary operators need for execution an operand. They are always written in prefix notation. The operators can be grouped with parentheses: The two variants

 <Operator><Evaluator>

and

 (<Operator><Evaluator>)

have as standalone expressions precisely the same semantics. The parenthesis variant exists to override operator precedence.

The order of precedence is as follows, ordered weak to strong binding:

  • logical disjunction
  • logical conjunction
  • equality, inequality
  • less, less-equal, greater, greater-equal
  • plus, binary minus
  • times, divided
  • logical negation
  • unary minus

In the following, the operators are ordered by precedence, stronger binding last.

Boolean Negation

The boolean negation evaluates to "1" if its argument evaluates to a representation of boolean false. Otherwise it evaluates to "0". Representations of boolean false are the empty std::string and every std::string that is a numerical representation of zero. Every other std::string represents boolean true.

Its syntax is

 ! <Evaluator>

The whitespace is optional.

Unary minus

The unary minus operator negates its argument. If the argument is an integer or a floating point number then it is negated as integer resp. floating point number. Otherwise the unary minus operator returns "NaN".

The syntax for unary minus is:

 - <Evaluator>

The whitespace is optional.

Binary Operators

Binary operators need for execution two operands. They are always written in infix notation. The operators can be grouped with parentheses: The two variants

 <Evaluator><Operator><Evaluator>

and

 (<Evaluator><Operator><Evaluator>)

have as standalone expressions precisely the same semantics. The parenthesis variant exists to override operator precedence:

 2 + 3 * 4

is evaluated to 2 + 12, then finally 14.

 (2 + 3) * 4

is evaluated to 5 * 4, then finally 20.

The order of precedence is as follows, ordered weak to strong binding:

  • the ternary operator
  • logical disjunction
  • logical conjunction
  • equality, inequality
  • less, less-equal, greater, greater-equal
  • plus, binary minus
  • times, divided
  • logical negation
  • unary minus

In the following, the operators are ordered by precedence, stronger binding last.

Boolean Disjunction

The boolean disjunction evaluates to "1" if one or both of its arguments evaluate to a representation of boolean true. Otherwise it evaluates to "0". Representations of boolean false are the empty string and every string that is a numerical representation of zero. Every other string represents boolean true. Currently, both arguments are always evaluated. This may change in future versions.

Its syntax is

 <Evaluator> || <Evaluator>

The whitespace is optional.

Boolean Conjunction

The boolean conjunction evaluates to "1" if both of its arguments evaluate to a representation of boolean true. Otherwise it evaluates to "0". Representations of boolean false are the empty string and every string that is a numerical representation of zero. Every other string represents boolean true. Currently, both arguments are always evaluated. This may change in future versions.

Its syntax is

 <Evaluator> && <Evaluator>

The whitespace is optional.

Equality and Inequality

The equaliy operator evaluates to "1" if both of its arguments are equal. Otherwise it evaluates to "0". The inequality operator evaluates to "0" if both of its arguments are equal. Otherwise it evaluates to "1". If both arguments can be interpreted as integers then the represented values are compared. Otherwise, if both arguments can be interpreted as floating point numbers then the represented values are compared. In all other cases the arguments are treated as strings.

Its syntax is for equality

 <Evaluator> == <Evaluator>

and for inequality

 <Evaluator> != <Evaluator>

The whitespace is optional.

Less, Less-Equal, Greater, and Greater-Equal

These operators evaluate to "1" if their arguments compare respectively. Otherwise they evaluate to "0". If both arguments can be interpreted as integers then the represented values are compared. Otherwise, if both arguments can be interpreted as floating point numbers then the represented values are compared. In all other cases the arguments are treated as strings.

The syntaxes for less, less-equal, greater, and greater-equal in this order are

 <Evaluator> < <Evaluator>
 <Evaluator> <= <Evaluator>
 <Evaluator> > <Evaluator>
 <Evaluator> >= <Evaluator>

The whitespace is optional.

Plus and Minus

While both operators have the same priority, they accept different kinds of arguments. If the arguments are both integers then they are added resp. subtracted as integers. If the arguments are both floating point numbers then they are added resp. subtracted as floating point numbers. Otherwise the plus operator concatenates the arguments as strings. Opposed to this, the minus operator returns "NaN".

The unary minus is an operator distinct from the binary minus operator defined here. It has a higher priority.

The syntaxes for plus and minus in this order are

 <Evaluator> + <Evaluator>
 <Evaluator> - <Evaluator>

The whitespace is optional.

Times and Divided

The times operator and the divided operator perform the respective arithmetic operations. If the arguments are both integers then they are multiplied as integers. Otherwise, if the arguments are both floating point numbers then they are multiplied resp. divided as floating point numbers. Division does treat integers like floating point numbers. If one or both arguments are no numbers then both the operators return "NaN".

The syntaxes for plus and minus in this order are

 <Evaluator> * <Evaluator>
 <Evaluator> / <Evaluator>

The whitespace is optional.

The Ternary Operator

The ternary operator needs for execution three operands. If the first operand evaluates to boolean true then it evaluates to what the second operand evaluates. Otherwise it evaluates to what the third operand evaluates.

The two variants

 <Evaluator>?<Evaluator>:<Evaluator>

and

 (<Evaluator>?<Evaluator>:<Evaluator>)

have as standalone expressions precisely the same semantics. The parenthesis variant exists to override operator precedence. For the precendence, see the binary operators.

String Endomorphisms

String endomorphisms are functions with one argument. Many of them help to normalize or check the value of its argument. They always first let their argument be evaluated. Their syntax is always

 <Function Name>(<Evaluator>)

Number Check, Normalizer and Suffix

The function number turns its argument into a number. If its argument starts with a number then number returns that number in a normalized format. Otherwise it returns "NaN". The function is_number checks whether its argument starts with a number. It returns "1" if its argument can be parsed as a number and "0" otherwise. The function suffix returns the suffix if any after the number in its argument. If the argument does not start with a number then it returns the empty string.

Their syntaxes are

 number(<Evaluator>)

resp.

 is_number(<Evaluator>)

resp.

 suffix(<Evaluator>)

Number Manipulation

since v0.7.58

The function abs interprets its argument as a number and returns its absolute value.

Its syntax is

 abs(<Evaluator>)

Date Check and Normalizer

The function date turns its argument into a number representing a date. If its argument is a date then date returns the number representing its argument's value. Otherwise it returns "NaD". The return value can be used for comparison operations only, it can't be used for any kind of calculations (e.g. time differences).

The function is_date checks whether its argument represents a date. It returns "1" if its argument can be parsed as a date and "0" otherwise.

A string is parsed for a date as follows:

  • the first group of digits is understood as year
  • the next group of digits if present is understood as month
  • then the next group if present is understood as day
  • if more groups of digits are present then they are understood as hour, minute, second

To be a date the year must be bigger than 1000, the month if present less or equal 12, the day if present less or equal 31, the hour if present less or equal 24, and the minute and second if present less or equal 60.

The date parser may get more liberal in future versions and accept more representations of dates.

The functions' syntax is

 date(<Evaluator>)

resp.

 is_date(<Evaluator>)

Geometry Endomorphisms

Geometry endomorphisms are functions with one argument. Many of them help to normalize or check the value of its argument. They always first let their argument be evaluated. Their syntax is always

 <Function Name>(<Evaluator>)

Center

since v0.7.55

The function center returns the center of its argument. It expects a function that evaluates to a geometry. It then delivers the point that is at the center of the bounding box of the geometry.

Its syntax is

 center(<Evaluator>)

Trace

since v0.7.55

The function trace returns the trace of its argument. It expects a function that evaluates to a geometry. It then delivers a collection of all segments and nodes that appear in its input. Ways are split at points that are explicitly in the set and at points that belong to more than one way in the set. Every node and segment is contained at most once.

Its syntax is

 trace(<Evaluator>)

Hull

since v0.7.55

The function hull returns the convex hull of its argument. It expects a function that evaluates to a geometry It then delivers a polygon without holes that contains all of its arguments.

Its syntax is

 hull(<Evaluator>)


List Represented Set Operators

Sometimes there is a need to represent multiple values in a tag's value. Although by no means mandated by the data format, the de-facto solution is to represent a set of values by a a semi-colon separated list of those values.

This section offers some functions to make handling of these lists easier. Currently, the delimiter is hard-coded to a semi-colon. For the sake of simplicity, leading or trailing white space at each list entry is ignored.

Note also that the lists are understood as sets. This means that the order of list elements does no matter.

List Represented Set Theoretic Operators

lrs_in

since v0.7.55

The function lrs_in returns "1" if its first argument is contained in the second argument treated as set. It returns "0" otherwise.

The function's syntax is

 lrs_in(<Evaluator>, <Evaluator>)
lrs_isect

since v0.7.55

The function lrs_isect returns the intersection of its two arguments treated as sets. If the arguments have no values in common then the empty string is returned.

The function's syntax is

 lrs_isect(<Evaluator>, <Evaluator>)
lrs_union

since v0.7.55

The function lrs_union returns the union of its two arguments treated as sets.

The function's syntax is

 lrs_union(<Evaluator>, <Evaluator>)

List Represented Set Statistic Operators

lrs_min

since v0.7.55

The function lrs_min returns the minimum of the elements in its argument treated as set. If all entries are numbers then the comparsion is numerical.

The function's syntax is

 lrs_min(<Evaluator>)
lrs_max

since v0.7.55

The function lrs_max returns the maximum of the elements in its argument treated as set. If all entries are numbers then the comparsion is numerical.

The function's syntax is

 lrs_max(<Evaluator>)

Set Key-Value Evaluator

Sets can have not only members. The may get assigned properties by other statements.

An example is the property "val": This property contains inside a "for"-loop the respective value of the current loop.

The syntax is

 <Set>.<Property>

As opposed to most other situations, it is mandatory to explicitly state the set.

Спеціальний синтаксис

Коментарі

В мові Overpass QL дозволяються коментарі такого ж стилю як у сирцях мов C, C++, Javascript або CSS:

  out; // A single line comment
  /* Comments starting with slash asterisk must always be closed with an asterisk slash. */
  /* But they can span
         multiple lines. */

Extended Overpass Turbo Queries

Extended Overpass Turbo Queries are not part of the Overpass QL language specification. However, Overpass QL is a core component of code generated by the Overpass Turbo Query Wizard, and knowing about the shortcuts Extended Overpass Turbo Queries provide is useful when querying an Overpass Turbo server. It is likely that you will at some point run into this syntax when viewing examples of Overpass Turbo queries.

Extended Overpass Turbo Queries may be identified by double braces, {{ }}. For a full list of these queries and their purposes, see Extended Overpass Turbo Queries.

Escaping

The following C-style escape sequences (also defined in Javascript) for representing characters are recognized:

  • \n escapes a newline
  • \t escapes a tabulation
  • \" or \' escapes the respective quotation mark
  • \\ escapes the backslash
  • \u#### (the hash characters stand for four hexadecimal digits) escapes the respective unicode UTF-16 code unit, see Unicode escape sequences.
    Note that the database encodes characters in UTF-8 on 1 byte (only characters in the 7-bit US-ASCII characters subset in the range U+0000..U+007F) or more. All characters that that are assigned a Unicode scalar value in the standard 17 planes are encoded as UTF-8.
    However, this syntax only supports characters assigned in the BMP (Basic Multilingual Plane), excluding surrogates which are not Unicode characters and have no valid UTF-8 encoding (even if code points assigned to surrogates have a 16-bit scalar value). Non-ASCII characters in the BMP are encoded with UTF-8 on 2 bytes (in the range U+0080..U+07FF), or 3 bytes (in the range U+0800..U+FFFF, minus surrogates in the range U+D800..U+DFFF).
    Unicode characters outside the BMP can be represented in UTF-16 as a pair of surrogates: only valid pairs of UTF-16 surrogates (a high surrogate in U+D800..U+DBFF immediately followed by a low surrogate in U+DC00..U+DFFF) are convertible to UTF-8 in the database, and can be escaped as \uD###\uD### (the result of escaping invalid pairs of surrogates or unpaired surrogates is undefined); these valid escaped pairs of surrogates will be internally converted to UTF-8-encoded sequences of 4 bytes (in supplementary planes 1 to 16); characters in the last valid supplementary planes 15 and 16, assigned only for private use, are supported but not useful in OSM data as they are not interoperable.

In general, there is currently no support for the common escaping syntax \U000##### used in modern C to represent a codepoint in any one of the 17 valid Unicode planes (excluding surrogates), and not even for arbitrary 8-bit bytes with the common escaping syntax \x## (defined in C independently of the encoding used). As much as possible escaping should be avoided if it's not needed, and valid UTF-8 used directly in requests.

File extension

When an Overpass QL query should be saved to a file, please use the .overpassql file extension. This way, the syntax of the file is immediately clear and unique to Overpass QL, making it easy to search for documentation. Also, syntax highlighting engines can rely on a unique file extension, too.

Note that other currently popular file extensions like .ql, .oql, .osm, .query or even .txt are not unique to Overpass QL, and thus syntax highlighting and/or other people might be confused about the file format.

Misc features

Map way/relation to area (map_to_area)

The map_to_area statement maps OSM object ids for relations to their Overpass API area id counterpart. Closed ways are passed from the input set to the output set. Thus you can use the output as a complete list of relevant areas.

This is done by applying the following mapping rules inside Overpass API:

  • For relations: add 3600000000 to the relations's OSM id.

Example:

  rel(62716);
  out;              // output relation 62716
  map_to_area;      // map OSM relation to Overpass API area by adding 3600000000 to its id
  out;              // output area 3600062716

The main use case of this statement is to search for objects inside an area, which is again inside another area ("area in area query").

Notes:

  • The Overpass API internal area creation job does not create an area for each and every relation in OSM. If an area does not exist for a given relation, map_to_area will simply skip this object without adding an area. Otherwise the area will be returned but with its geometry as it was when it was last created or updated by an internal background process on the Overpass server, and it may be different from the most recent geometry loaded from the relation element in the OSM database.
  • Using areas in queries instead of actual OSM elements may speed up the Overpass queries as these geometries don't need to be fully loaded from possibly many child elements from the OSM database, and then converted by connecting ways with common nodes.
  • Also not all relations and ways may convert to a valid area (even if their tags normally imply that they should be valid areas) if they don't create properly closed rings.
  • see also: Overpass API/Areas

The following examples outline some possible use cases for this statement:

Example 1: Find all pubs in the inner city of Cologne

Querying only for an area named "Innenstadt" would return quite a number of areas, not limited to Cologne.

try it yourself in overpass-turbo
area[name="Köln"]->.b;
rel(area.b)[name="Innenstadt"];
map_to_area -> .a;
node(area.a)[amenity=pub];
out meta;

Example 2: Find all municipalities (admin_level=8 !) in Hessen without fire station

try it yourself in overpass-turbo
area[admin_level=4]["name"="Hessen"][boundary=administrative]->.boundaryarea;
( node(area.boundaryarea)["amenity"="fire_station"];
  way(area.boundaryarea)["amenity"="fire_station"];
  >;
) ->.a;

.a is_in -> .b; 
area.b[admin_level=8] -> .bf; 

rel(area.boundaryarea)[admin_level=8];
map_to_area -> .bllf;

(.bllf; - .bf; );
rel(pivot);
(._;>;);
out;

Example 3ː Count the number of pharmacies per county

try it yourself in overpass-turbo
[out:csv(::"type",::"id", name, admin_level,::"count")];
area[name="Saarland"][boundary];
 rel(area)[boundary][admin_level=6];
 map_to_area;
 foreach->.d(
   (.d;);out; 
   (node(area.d)[amenity=pharmacy];
    way(area.d)[amenity=pharmacy];
    relation(area.d)[amenity=pharmacy];);
   out count;
 );

Example 4ː Named input set

try it yourself in overpass-turbo
rel(62716)->.b;
  .b out;
  .b map_to_area;
  out;

Example 5ː Find the number of bicycle parking facilities per county in California

try it yourself in overpass-turbo
[out:csv(::"type",::"id", name, admin_level,::"count")];
area[name="California"][boundary];
 rel(area)[boundary][admin_level=6];
 map_to_area;
 foreach->.d(
   (.d;);out; 
   (node(area.d)[amenity=bicycle_parking];
    way(area.d)[amenity=bicycle_parking];
    relation(area.d)[amenity=bicycle_parking];);
   out count;
 );

Example 6ː Find all primary roads in London not part of a bus route

try it yourself in overpass-turbo
area[name="London"]->.a;
way(area.a)[highway=primary]->.primary_roads;
rel(area.a)[route=bus];
way(r)->.bus_routes;
(.primary_roads; - .bus_routes;);
out body;
>;
out skel qt;

Example 7ː Find Museums in Paris with Nearby Transportation within 50 Meters

try it yourself in overpass-turbo
area[name="Paris"]->.a;
(
  node(area.a)["tourism"="museum"];
  way(area.a)["tourism"="museum"];
)->.museums;

(
  node(around.museums:50)["highway"="bus_stop"];
  way(around.museums:50)["highway"="bus_stop"];
  node(around.museums:50)["railway"="tram_stop"];
  way(around.museums:50)["railway"="tram_stop"];
  node(around.museums:50)["railway"="subway_entrance"];
  way(around.museums:50)["railway"="subway_entrance"];
);

/*added by auto repair*/
(._;>;);
/*end of auto repair*/
out meta;

Example 8ː Find cafes that are closer than 20 meters from a pedestrian street

try it yourself in overpass-turbo
area[name="Berlin"]->.a;
way(area.a)[highway=pedestrian]->.pedestrian_streets;
way(area.a)[amenity=cafe]->.cafes;
way.pedestrian_streets(around.cafes:20);
/*added by auto repair*/
(._;>;);
/*end of auto repair*/
out meta;


Example 9ː Find Natural Reservations that are bigger than 10 km length in Colorado and that do not have a hiking route inside them.

try it yourself in overpass-turbo
area[admin_level=4]["name"="Colorado"]->.boundaryarea;
( node(area.boundaryarea)["leisure"="nature_reserve"];
  way(area.boundaryarea)["leisure"="nature_reserve"];
  >;
) ->.a;
.a is_in -> .b;
way.b["route"="hiking"] -> .hiking_routes;
(way(area.boundaryarea)(if: length() > 10000)["leisure"="nature_reserve"]; -  .hiking_routes;);
/*added by auto repair*/
(._;>;);
/*end of auto repair*/
out;

Example 10ː Find parks in Berlin that have a playground inside or around 500 meters from the park

try it yourself in overpass-turbo
area[name="Berlin"]->.region;
rel(area.region)[leisure=park];
map_to_area -> .parks;
node(area.parks)[leisure=playground];
way(area.parks)[leisure=playground];
out;
node(area.parks)[leisure=playground] -> .playgrounds;
node.playgrounds(around:500);
out ;


Example 11ː Find longer than 3 km paved runway in the world

try it yourself in overpass-turbo
way["aeroway"="runway"]["surface"="paved"](if: length() > 3000);
/*added by auto repair*/
(._;>;);
/*end of auto repair*/
out meta;

Example 12ː Find all bike rental stations in San Francisco within 50 meters of a railway station

try it yourself in overpass-turbo
area[name="San Francisco"]->.sf;
node(area.sf)["amenity"="bicycle_rental"]->.bike_rental;
node(around.bike_rental:50)["railway"="station"]->.station;
node(around.station:50)["amenity"="bicycle_rental"]->.filtered_bicycle_rental;

(
  .filtered_bicycle_rental;
  .station;
);
out meta;



Notes

See also