[[TranslatedPages(revision=146,outdated=Страница переведена не полностью)]] [[PageOutline(1-10,Содержание)]] Эта страница документирует подробности реализации языка [osmwiki:MapCSS/0.2 MapCSS] в JOSM. Он используется в следующих элементах JOSM: * [wikitr:/Styles Стили отрисовки карты] * [wikitr:/Rules Правила валидатора] * [wikitr:/Help/Action/Search Диалог поиска] == Общая структура == Таблица стилей MapCSS содержит правила в следующей форме: {{{ #!mapcss selector { prop: value; /* ... */ prop: value; /* and/or */ set: class; set: .class; } }}} Алгоритм поиска стилей для заданного объекта таков: {{{ - для каждого правила: если селектор применим к объекту, задать свойства из блока { } - проанализировать последний список свойств и сгенерировать стили из него }}} MapCSS использует формат '''комментариев''' из CSS (`/* ... */`). Заметьте, что при комментировании больших частей файла MapCSS некоторые конструкции могут вызвать непредвиденный конец комментария, например: {{{ #!mapcss /* *[highway][name =~ /^R(\.|:)? .*/] { /* группа символов в конце регулярного выражения приводит к непредвиденному завершению комментария */ throwWarning: tr("foo"); } */ }}} == Селекторы == ''Селекторы'' — это выражения для фильтрации правил MapCSS. Правило применяется к объекту карты, только если его селектор соответствует объекту. Селекторы в MapCSS отличаются от стандартных в CSS для WWW. MapCSS поддерживает лишь подмножество стандартных селекторов CSS, но в него добавлены дополнительные селекторы, требующиеся для данных OSM. Некоторые простые примеры: {{{ #!mapcss /* применяется к линиям с тегом highway=residential */ way[highway=residential] { /* the styles */} /* применяется к новым замкнутым линиям на слое 1, если они имеют тег amenity=parking и access=customers, и если * уровень масштаба в диапазоне от 11 до 14 */ way|z11-14[amenity=parking][access=customers]:closed:new::layer_1 {...} area[amenity=parking][access=customers], area[amenity=parking][!access] {...} relation[type=route][route=foot] > way::relation_underlay {..} }}} Другие элементы ('''type'''-, '''zoom'''- , '''condition''' selector, '''pseudo classes''', '''layer identifier''', '''grouping''' и '''child combinator''') поясняются ниже. === Селекторы типа === {{{#!th align=left valign=top '''Селектор''' }}} {{{#!th align=left valign=top '''Описание''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top * }}} {{{#!td align=left valign=top Соответствует любому объекту }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{node}}}, {{{way}}}, {{{relation}}} }}} {{{#!td align=left valign=top Соответствует объектам OSM заданного типа. }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{area}}} }}} {{{#!td align=left valign=top Соответствует любым областям, независимо от того, сформирован ли контур области одной линией или же набором линий, соединённых вместе отношением. {{{ #!mapcss area[natural=beach] {...} /* ... равнозначно ... */ way[natural=beach], relation[type=multipolygon][natural=beach] {...} }}} Заметьте, что {{{area}}} выбирает также незамкнутые линии, так что может быть полезно добавить псевдокласс {{{:closed}}}. Валидатор JOSM выдаст предупреждение для незамкнутых линий имеющих стиль area. }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{meta}}} }}} {{{#!td align=left valign=top Селектор {{{meta}}} начинает особое правило, которое должно располагаться в начале файла. Оно даёт некоторую общую информацию о таблице стилей. Все программы, поддерживающие MapCSS, должны быть способны разобрать эту секцию без ошибок, поэтому не используйте экзотических синтаксических выражений в данной части. {{{ #!mapcss meta { title: "Parking lanes"; /* заголовок, отображаемый в меню */ icon: "images/logo.png"; /* маленький значок, отображаемый в меню рядом с заголовком */ version: "1.2"; /* версия стиля */ description: "..."; /* одно или два предложения, описывающие стиль */ author: "..."; /* автор(ы) стиля */ link: "http://..."; /* URL веб-страницы стиля */ min-josm-version: 6789; /* минимальная версия JOSM, в которой этот стиль работает */ } }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{canvas}}} }}} {{{#!td align=left valign=top Некоторая информация стиля, не специфичная для точек, линий или отношений. {{{ #!mapcss canvas { fill-color: #ffffea; /* прежний background-color устарел, начиная с r7110 */ default-points: false; default-lines: false; } }}} {{{#!th '''Ключ''' }}} {{{#!th '''Описание''' }}} {{{#!th '''Формат значения''' }}} {{{#!th '''Значение по умолчанию''' }}} |- {{{#!td {{{fill-color}}} }}} {{{#!td Указывает общий цвет заливки/фона (`background-color` устарел, начиная с r7110). }}} {{{#!td ''Цвет'' }}} {{{#!td align=center {{{black}}} }}} |- {{{#!td {{{default-points}}} }}} {{{#!td Должен ли используемый по умолчанию стиль точки добавляться к точкам, к которым не применим ни один стиль. }}} {{{#!td ''Логический'' }}} {{{#!td align=center {{{true}}} }}} |- {{{#!td {{{default-lines}}} }}} {{{#!td Должен ли используемый по умолчанию стиль линии применяться к линиям, к которым не применим ни один стиль. }}} {{{#!td ''Логический'' }}} {{{#!td align=center {{{true}}} }}} }}} === Селекторы потомков === Если точка является частью линии, мы называем её ''потомком'' (child) этой линии. Аналогично, если точка, линия или отношение является участником отношения, то мы называем их ''потомками'' этого отношения. В MapCSS можно использовать '''селектор потомков''', который соответствует объекту, только если соответствует и родительскому объекту и его потомку. Пример: {{{ #!mapcss /* * соответствует только линии, являющейся потомком отношения с тегами * type=route и route=foot */ relation[type=route][route=foot] > way {...} }}} Примечания: * Zoom selector and Layer identifier are only relevant for the part to the right of the > sign. * Функции ''prop()'' и ''is_prop_set()'' поддерживаются только на стороне справа от знака >. * Функции ''parent_tag'' и ''parent_tags'' (см. ниже) можно использовать для доступа к тегам из родителя(ей). * Для совместимости со стандартом MapCSS 0.2, `relation[type=route][route=foot] way {/*...*/}`, без знака `>` также поддерживается. However, no [[#Linkselector]] may be specified in this case. === Селекторы родителей === В дополнение к селектору потомков, JOSM поддерживает '''селектор родителей'''. Обратите внимание, что селектор родителей — это специфичное для JOSM расширение MapCSS, не присуствующее в других реализациях MapCSS. Подобно селектору потомков, селектор родителей соответствует объекту, только если соответствует и родительскому объекту, и потомку. В отличие от селектора потомков, используется символ <. В отличие от селектора потомков, будет "выбран" родительский объект. Другими словами, свойства в блоке декларации { {{{...}}} } применяются к объекту справа от знака "<". Пример: {{{ #!mapcss /* * соответствует дороге, имеющей по меньшей мере одну точку с тегом traffic_calming=* */ node[traffic_calming] < way[highway] {...} }}} === Селекторы условий === Селекторы могут включать ряд условий. Если какое-то из этих условий не истинно, то селектор не соответствует объекту и правило стиля не применяется. An '''attribute condition''' specifies a condition on a tag of an OSM object. [=#condition_selector_operators] {{{#!th align=left valign=top '''Оператор''' }}} {{{#!th align=left valign=top '''Описание''' }}} {{{#!th align=left valign=top '''Пример''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `=` }}} {{{#!td align=left valign=top Точное соответствие значения. }}} {{{#!td align=left valign=top {{{ #!mapcss way[highway=residential] /* без кавычек — всегда без учёта регистра символов */ node[name="My name"] /* используйте кавычки, если значение содержит пробелы или если важен регистр символов */ node["MY_Special_TAG"="another value"] /* используйте кавычки для имён тегов, если важен регистр символов */ node["ÖPVN"=tram] /* используйте кавычки для ключей тегов со специальными символами */ /* заметьте, что на данный момент такие ключи не часто встречаются в OSM */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `!=` }}} {{{#!td align=left valign=top Несоответствие значения }}} {{{#!td align=left valign=top {{{ #!mapcss way[highway!=residential] /* без кавычек — всегда без учёта регистра символов */ node[name!="My name"] /* используйте кавычки, если значение содержит пробелы или если важен регистр символов */ node["MY_Special_TAG"!="another value"] /* используйте кавычки для имён тегов, если важен регистр символов */ node["name:fr"!="mon nome"] /* используйте кавычки для ключей тегов со специальными символами, например, двоеточием*/ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `<`, `>`, `<=`, `>=` }}} {{{#!td align=left valign=top Сравнение для числовых значений. }}} {{{#!td align=left valign=top {{{ #!mapcss node[population >= 50000] /* население больше или равно 50000 */ node[ele = 3000] /* возвышение ровно на 3000 метров */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{^=}}} }}} {{{#!td align=left valign=top Совпадение начала }}} {{{#!td align=left valign=top {{{ #!mapcss node[name ^= "myprefix"] /* значение начинается с 'myprefix' */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `$=` }}} {{{#!td align=left valign=top Совпадение окончания }}} {{{#!td align=left valign=top {{{ #!mapcss node[name $= "mypostfix"] /* значение заканчивается на 'mypostfix' */ }}} }}} |----------------------------------------------- {{{#!td align=left valign=top `*=` }}} {{{#!td align=left valign=top Совпадение подстроки }}} {{{#!td align=left valign=top {{{ #!mapcss node[name *= "my substring"] /* значение содержит подстроку 'my substring' */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `~=` }}} {{{#!td align=left valign=top Наличие в списке }}} {{{#!td align=left valign=top {{{ #!mapcss *[vending~=stamps] /* значение тега 'vending' состоит из списка разделённых точкуой с запятой значений, */ /* и одно из этих значений равно 'stamps' */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `=~` }}} {{{#!td align=left valign=top Соответствие [https://download.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum регулярному выражению] }}} {{{#!td align=left valign=top {{{ #!mapcss *[name=~/^My_pattern.*/] /* значение тега 'name' соответствует регулярному выражению '^My_pattern.*' */ /* Заметьте, что регулярное выражение должно быть заключено в /.../ */ }}} Нечувствительное к регистру условие можно включить с помощью встроенного flag expression `(?i)` (см. [https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#CASE_INSENSITIVE Pattern.CASE_INSENSITIVE]). {{{ #!mapcss *[name =~ /^(?U)(\p{Lower})+$/] /* имя состоит только из символов Юникода в нижнем регистре */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `!~` (начиная с r6455) }}} {{{#!td align=left valign=top несоответствие [https://download.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum регулярному выражению] }}} {{{#!td align=left valign=top {{{ #!mapcss *[surface!~/paved|unpaved/] }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `∈` ([http://www.fileformat.info/info/unicode/char/2208/index.htm U+2208], с r6609) }}} {{{#!td align=left valign=top является элементом ... }}} {{{#!td align=left valign=top {{{ #!mapcss node[amenity=parking] ∈ *[amenity=parking] { throwWarning: tr("{0} внутри {1}", "amenity=parking", "amenity=parking"); } }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `⧉` ([http://www.fileformat.info/info/unicode/char/29c9/index.htm U+29C9], с r6613) }}} {{{#!td align=left valign=top пересечение }}} {{{#!td align=left valign=top {{{ #!mapcss area:closed:areaStyle ⧉ area:closed:areaStyle { throwOther: tr("Перекрывающиеся области"); } }}} принимает во внимание тег `layer`, если он задан (начиная с r12986) }}} Начиная с r6554, возможно предварить "значение" (т.е. выражение после оператора) символом `*` для его "разыменования" (i.e., obtain consider it as another key and obtain its value). Таким образом, `[key1 = *key2]` или `[key1=*key2]` сравнивает значение `key1` со значением `key2`, а `[key =~ */pattern/]` рассматривает значение ключа `pattern` как регулярное выражение и сравнивает его со значением ключа `key`. In addition, you can test whether a tag is present or not: {{{#!th align=left valign=top '''Условие''' }}} {{{#!th align=left valign=top '''Пример''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Наличие тега }}} {{{#!td align=left valign=top {{{ #!mapcss way[highway] /* matches any way with a tag 'highway' */ way["VALSOU"] /* use quotes if case sensitive matching is required */ way["name:fr"] /* use quotes if the tag name includes special caracters (white space, colons, etc.) */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Отсутствие тега }}} {{{#!td align=left valign=top {{{ #!mapcss way[!highway] /* matches any way which does not have a tag 'highway' */ way[!"VALSOU"] /* use quotes if case sensitive matching is required */ way[!"name:fr"] /* use quotes if the tag name includes special caracters (white space, colons, etc.) */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Presence of tag by [https://download.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum Regular expression] match (since r6547) }}} {{{#!td align=left valign=top {{{ #!mapcss way[/^addr:/] /* matches any `addr:*` key */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Absence of tag by Regular expression match }}} {{{#!td align=left valign=top {{{ #!mapcss way[!/^addr:/] /* соответствует любой линии, не имеющей тега 'addr:*' */ }}} }}} You can test whether the value of a tag is logical truth value. The value is evaluated to true, if it is either "yes", "true", or "1". All other values are evaluated to false. {{{#!th align=left valign=top '''Условие''' }}} {{{#!th align=left valign=top '''Пример''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Testing for truth value }}} {{{#!td align=left valign=top {{{ #!mapcss way[oneway?] /* matches any way with a truth value in the tag 'oneway' */ }}} }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top Testing for false value (since r6513) }}} {{{#!td align=left valign=top {{{ #!mapcss way[oneway?!] /* matches any way with a false value in the tag 'oneway' */ }}} }}} === Селекторы территории === Можно проверить, располагается объект внутри некоторой территории, или за её пределами. В JOSM есть встроенная база данных для этого. Файл территорий — это osm-файл, его можно скачать [/export/HEAD/josm/trunk/data/boundaries.osm здесь] и открыть в JOSM для исследования [attachment:wiki:Help/Styles/MapCSSImplementation:boundaries.png (снимок экрана)]. Он содержит границы всех стран мира. Для повышения производительности границы упрощены. В особых случаях они могут быть уточнены по запросу. Территории "тегированы" их [https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 кодами ISO_3166-1_alpha-2]. Для США, Канады, Китая, Индии и Австралии имеются дополнительные границы их территориального деления. Смотрите в следующих примерах, как использовать селекторы территории. Селекторы территории менее полезны с стилях отрисовки карты, где они могут быть очень ресурсоёмкими, но они гораздо более полезны для [wikitr:/Help/Validator/MapCSSTagChecker правил валидатор, основанных на mapcss]. Для выбора территорий с левосторонним или правосторонним движением существует более простой способ, смотрите [#PseudoClasses Псевдоклассы]. See #10387 for main implementation of this feature. {{{ #!mapcss node[inside("FR")] /* соответствует любой точке, находящейся во Франции (включая все её заморские территории)*/ node[inside("FX")] /* соответствует любой точке в Метрополии Франции (т.е. только её европейской материковой части с ближайшими островами, включая Корсику) */ node[inside("EU")] /* соответствует любой точке внутри Европейского Союза */ node[inside("FR,DE")] /* соответствует любой точке во Франции __ИЛИ__ в Германии */ node[inside("US-FL")] /* соответствует любой точке в США, штат Флорида */ node[outside("FR")] /* соответствует любой точке за пределами Франции */ node[outside("FR,DE")] /* соответствует любой точке за пределами Франции __И__ за пределами Германии */ node[inside("US")][outside("US-FL")] /* соответствует любой точке в США, за исключением штата Флорида */ }}} === Link selector === In a child selector, you can formulate conditions on the link between a parent and a child object. If the parent is a relation, you can formulate conditions for the ''role'' a member objects has in this relation. {{{ #!mapcss relation[type=route] >[role="link"] way { /* matches any way which is a member of route relation with role 'link' */ color: blue; } }}} {{{#!th align=left valign=top '''Оператор''' }}} {{{#!th align=left valign=top '''Описание''' }}} {{{#!th align=left valign=top '''Пример''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top `=` }}} {{{#!td align=left valign=top Exact match of the role name. The name name {{{role}}} is compulsory in this context. }}} {{{#!td align=left valign=top {{{ #!mapcss relation >[role=residential] way /* without quotes always case insensitive */ relation >[role="My name"] way /* use quotes for if the role value includes spaces or if case sensitive matching is important */ }}} }}} The operators {{{!=, ^=, $=, *=, and ~=}}} are supported too. Please refer to [#condition_selector_operators condition selector operators]. Nodes in ways and members in relations are ordered. You can formulate conditions on the position of a node in a way or a member object in a relation. Positive numbers count from first to last element, negative numbers (since r8236) count from last to first element. {{{ #!mapcss relation[type=route] >[index=1] way { /* matches the first way which is a member of route relation */ color: blue; } way >[index=-1] node { /* matches the last node of a way */ symbol-stroke-color: green; } way!:closed >[index=1] node!:connection, way!:closed >[index=-1] node!:connection { /* matches all single way end nodes */ symbol-stroke-color: green; } }}} === Селекторы масштаба === Селектор типа можно дополнить '''селектором масштаба'''. Он ограничит диапазон уровней масштаба, на которых применяется соответствующее правило MapCSS. {{{#!th align=left valign=top '''Пример''' }}} {{{#!th align=left valign=top '''Описание''' }}} |------------------------------------------------------------------------------- || {{{way|z12 {...} }}} || При уровне масштаба 12 || || {{{way|z13-15 {...} }}} || С 13 по 15 || || {{{way|z16- {...} }}} || 16 и выше || || {{{way|z-12 {...} }}} || 12 и ниже || || {{{way {...} }}} || при любом масштабе || The precise definition of scale ranges for each zoom level may change in the future. By rule of thumb you can expect to be approximately at zoom level ''n'' when imagery displays slippymap tiles of level ''n''. === Псевдоклассы === Смотрите в [/doc/org/openstreetmap/josm/gui/mappaint/mapcss/Condition.PseudoClasses.html Javadoc] актуальный в настоящее время список псевдоклассов, поддерживаемых в реализации MapCSS для JOSM. || {{{:closed}}} || истинно для линий, первая точка которых совпадает с последней (т.е. замкнутых линий) и для любых (полностью скачанных) отношений типа мультиполигон || || {{{:closed2}}} || то же, что и выше, но this one ignores if a mulipolygon is downloaded completely (с r9099) || || {{{:completely_downloaded}}} || истинно для отношений, у которых скачаны все участники (с r9099) || || {{{:new}}} || все новые объекты || || {{{:connection}}} || истинно для точек, которые используются более чем в одной линии || || {{{:unconnected}}} || истинно для точек, которые не входят в состав ни одной линии (с r6687) || || {{{:tagged}}} || объект, тегированный в понимании JOSM, т.е. объект имеет ключ тега кроме следующих: {{{source*, source_ref, note, comment, converted_by, created_by, watch*, fixme, FIXME, description, attribution}}} (версия r4008; in this list, {{{*}}} is a glob) || {{{:righthandtraffic}}} || true if there is right-hand traffic at the current location (since r7193); see [[left-right-hand-traffic]] for screenshot of areas || || {{{:clockwise}}} || Whether the way is closed and oriented clockwise, or non-closed and the 1st, 2nd and last node are in clockwise order. || || {{{:anticlockwise}}} || Whether the way is closed and oriented anticlockwise, or non-closed and the 1st, 2nd and last node are in anticlockwise order. || || {{{:unclosed_multipolygon}}} || true for fully loaded unclosed multipolygon relations (since r8252) || || {{{:open_end}}} || to select end nodes of unclosed multipolygon relations with `relation:unclosed_multipolygon >:open_end node` (since r8252) || || {{{:in-downloaded-area}}} || true if an object is within source area and false if in the hatched area (since r8495). || || {{{:selected}}} || true if an object is selected in the editor (since r9341). || || {{{:modified}}} || changed objects (since r7193). || You can also negate pseudo classes. E.g. {{{!:new}}} for all old objects. === Layer Identifier === Layers can be used to create more than one style for a single object. Here is an example: {{{ #!mapcss way[highway=secondary] { width: 3; color: yellow; } way[highway=tertiary] { width: 2; color: orange; } way[access][access!=yes]::non_public_access_layer { width: +2; color:red; dashes: 2; object-z-index:-1.0; } way[bridge]::bridge_layer { width: +3; color:#000080; opacity:0.5; object-z-index:1.0; } }}} This draws all secondary and tertiary roads in yellow and orange respectively. Any road with an access tag other than yes will get an extra line style below ('''{{{object-z-index:-1.0;}}}''') the main line. If that part of the street happens to be a bridge, it will also get a half transparent blue overlay. The relative width value ('''{{{width: +2;}}}''') refers to the width on the default layer (2 or 3 in this case). The name for the layer can be any identifier. If you omit the layer in the selector, this is the same as using {{{::default}}}. One more example: {{{ #!mapcss node[amenity=parking] { icon-image: "presets/vehicle/parking/parking.svg"; /* displays the josm internal parking icon in the default layer */ text: ref; /* displays the value of the key ref as text in the default layer */ } node[amenity=parking][fee=yes]::fee { icon-image: "presets/money/exchange.svg"; /* displays the josm internal exchange icon in the fee layer */ icon-offset-x: 14; /* shift the icon */ icon-offset-y: -12; /* shift the icon */ text: charge; /* displays the value of the key charge as text in the fee layer */ text-offset-x: 16; /* shift the text */ text-offset-y: 17; /* shift the text */ } }}} The result looks this way: [[Image(multiple_icons_and_texts.png)]] In addition, you can use the * layer to override and initialize all layers.[[br]] It overrides all existing subparts, so {{{ #!mapcss way::A { a; } way::B { b; } way::* { c; } }}} is equivalent to {{{ #!mapcss way::A { a; } way::B { b; } way::A { c; } way::B { c; } }}} And it initializes new subparts. In other words: {{{ #!mapcss way::* { a; } way::A { b; } }}} is equivalent to {{{ #!mapcss way::A {} way::* { a; } way::A { b; } }}} which is in turn the same as {{{ #!mapcss way::A { a; } way::A { b; } }}} or {{{ #!mapcss way::A { a; b; } }}} === Grouping === Rules with common declaration block can be grouped into one: {{{ #!mapcss area[landuse=forest] { color: green; width: 2; } area[natural=wood] { color: green; width: 2; } }}} is the same as {{{ #!mapcss area[landuse=forest], area[natural=wood] { color: green; width: 2; } }}} === Classes === You may assign classes to matched elements, and define other selectors using those classes: {{{ #!mapcss /* assigning classes */ selector { set class; /* or equivalently */ set .class; } /* matching classes */ way.class, node[foo=bar].class { /* ... */ } }}} Example for assigning/matching a class named `path`: {{{ #!mapcss way[highway=footway] { set path; color: #FF6644; width: 2; } way[highway=path] { set path; color: brown; width: 2; } way.path { text:auto; text-color: green; text-position: line; text-offset: 5; } }}} You can also negate classes. E.g. {{{way!.path}}} for all ways, which are not part of the class ''.path''. == @supports rule for conditional processing [''since 8087''] == @supports rules are used to skip a section of the style under certain conditions. Typically you want to use a feature which is introduced in a newer version of JOSM, but like to have a fall back style for users of older JOSM clients. Example: {{{ #!mapcss @supports (min-josm-version: 9789) { way[highway] { width: 4; color: orange; } /* fancy new stuff */ /* ... */ } @supports (max-josm-version: 9788) { way[highway] { width: 4; color: blue; } /* fall back mode, using more simple features */ /* ... */ } @supports (icon-offset-x) { /* only if icon-offset-x property is supported */ node[amenity] { icon-offset-x: 5; } } }}} The syntax closely matches the official [https://drafts.csswg.org/css-conditional/ css syntax]. The following conditions are supported: {{{#!th '''Condition''' }}} {{{#!th '''Description''' }}} |- {{{#!td ('''') }}} {{{#!td Check if a certain mapcss key is supported, e.g. `repeat-image` or `icon-offset-x`. }}} |- {{{#!td (min-josm-version: '''') }}} {{{#!td Only include {{{@supports}}} section when the current version of JOSM is greater than or equal to the specified number. }}} |- {{{#!td (max-josm-version: '''') }}} {{{#!td Only include {{{@supports}}} section when the current version of JOSM is lower than or equal to the specified number. }}} |- {{{#!td (user-agent: '''') }}} {{{#!td Only include {{{@supports}}} section when the name of the editor / renderer matches the given string. In JOSM, the only accepted value is {{{josm}}}. }}} Conditions can be combined with {{{and}}}: {{{ #!mapcss @supports (min-josm-version: 8087) and (max-josm-version: 8200) { /* only for JOSM versions 8087 to 8200 */ } }}} Other logical operators like {{{or}}} and {{{not}}} can also be used. Parentheses are needed if you want to combine different logical operators: {{{ #!mapcss @supports ((min-josm-version: 8087) and (max-josm-version: 8200)) or (user-agent: myEditor) { /* for JOSM version 8087 to 8200 and for the editor called "myEditor" */ } }}} Since @supports rules are only supported in JOSM 8087 and later, you should also specify this as minimum JOSM version in the meta selector: {{{ #!mapcss meta { min-josm-version: "8087"; /* This style uses @supports rules */ /* ... */ } }}} == Style settings == [[Help/Dialog/MapPaint/StyleSettings|Styles settings]] are used to provide the user settings to customize a mappaint style. The user can use them in the MapPaint dialog. Style settings are availible since r7450. The internal style provides style settings since r7454. Note that there are plans to extend the implementation of style settings (currently there are only boolean values supported), so the mapcss syntax for style settings could change in the future (see #10435). create a setting: {{{ #!mapcss setting::highway_casing { type: boolean; label: tr("Draw highway casing"); default: true; } }}} use a setting: {{{ #!mapcss way[highway][setting("highway_casing")] { casing-width: 2; casing-color: white; } }}} == Properties == === General properties === ||= '''Key''' =||= '''Description''' =||= '''Value Format''' =||= '''Default Value''' =|| || {{{z-index}}} || Specify the order the objects are drawn: The objects with higher z-index are drawn on top of objects with lower z-index || ''Number'' (can be negative) || 0 || || {{{major-z-index}}} || Similar to {{{z-index}}}, but it has higher priority than {{{z-index}}}. So if one object has a higher {{{major-z-index}}} than the other, it is drawn on top. If the {{{major-z-index}}} is the same, {{{z-index}}} decides. || ''Number'' (can be negative) || Depends on style element: area: 1, casing: 2, left-/right-casing: 2.1, line-pattern: 2.9, line: 3, point: 4, default-point: 4.1, line-text: 4.9, point-text: 5 || || {{{object-z-index}}} || Similar to {{{z-index}}}, but has lower priority. Controls the painting order for overlapping objects. E.g. for two crossing ways with text: Use {{{z-index}}} or {{{major-z-index}}} if you first want to draw the two lines and then the two captions. Use {{{object-z-index}}} if one of the ways should be completely on top of the other. || ''Number'' (can be negative) || 0 || || {{{modifier}}} || Better control, whether a default line / node symbol is generated by JOSM. This happens when there is no proper style ({{{modifier=false}}}) found on any layer. || {{{false}}} or {{{true}}} || {{{false}}} for the default layer and {{{true}}} for any other layer || Note that due to performance reasons the values for the three z-indexes are limited to 24 bit float values with max. 5 decimal digits. Currently the internal mappaint style uses values with max. 2 digits before and after the decimal separator. To avoid problems use values of z-indexes between -99.999 and +99.999. (See also #14485) === Icon and symbol styles === ||= '''Key''' =||= '''Description''' =||= '''Value Format''' =||= '''Default Value''' =|| || {{{icon-image}}} || The icon at node position. See also [wiki:Help/Styles/Images Images]. || ''Image'' || - || || {{{icon-opacity}}} || Opacity of the icon image || ''Opacity'' || 1.0 || || {{{icon-width}}} || Width of the icon. If only one of the properties {{{icon-width}}} and {{{icon-height}}} is given, the image will be scaled proportionally. The icon will keep the original size, if neither {{{icon-width}}} nor {{{icon-height}}} is set. || ''Number'' || - || || {{{icon-height}}} || Height of the icon. (See {{{icon-width}}}) || ''Number'' || - || || `icon-offset-x` || Shift the icon in horizontal direction (positive values to the right) (since r8085) || ''Number'' || 0 || || `icon-offset-y` || Shift the icon in vertical direction (positive values downwards) (since r8085) || ''Number'' || 0 || || `icon-rotation` || Rotate the icon clockwise or anti clockwise (negative value)(since r8260) || `[rad]`, `[rad]rad`, `[deg]°`, `[deg]deg`, `[grad]grad`, `[turn]turn` ([https://developer.mozilla.org/en/docs/Web/CSS/angle definition]) or a cardinal direction (e.g. `northeast` or `sw`); See also the functions `degree_to_radians`, `cardinal_to_radians`. || - || || `icon-position` || Define the position of the icon for areas. Same as `text-position` (since r11730). || {{{center}}}, {{{inside}}}, {{{line}}} || {{{center}}} || || {{{symbol-shape}}} || Display a symbol at the position of the node || {{{square}}}, {{{circle}}}, {{{triangle}}}, {{{pentagon}}}, {{{hexagon}}}, {{{heptagon}}}, {{{octagon}}}, {{{nonagon}}}, {{{decagon}}} || - || || {{{symbol-size}}} || Size of the symbol || ''Number'', can be relative ("+4") || 10 || || {{{symbol-stroke-width}}} || outline stroke width || ''Width'' || 1.0 if {{{symbol-stroke-color}}} is set || || {{{symbol-stroke-color}}} || line color || ''Color'' || {{{#FFC800}}} if {{{symbol-stroke-width}}} is set || || {{{symbol-stroke-opacity}}} || line opacity || ''Opacity'' || 1.0 || || {{{symbol-fill-color}}} || fill color for the shape || ''Color'' || {{{blue}}}, unless either {{{symbol-stroke-width}}} or {{{symbol-stroke-color}}} is set || || {{{symbol-fill-opacity}}} || fill opacity || ''Opacity'' || 1.0 || || {{{text-...}}}, {{{font-...}}} |||||| general text & font properties || || {{{text-anchor-horizontal}}} || horizontal text label placement || {{{left}}}, {{{center}}}, {{{right}}} || {{{right}}} || || {{{text-anchor-vertical}}} || vertical text label placement || {{{above}}}, {{{top}}}, {{{center}}}, {{{bottom}}}, {{{below}}} || {{{bottom}}} || Do not rely on the default values for {{{symbol-...}}} properties (except for {{{opacity}}}). They are intended for "quick & dirty" style sheets and should be set to an explicit value. === Line styles === ||= '''Key''' =||= '''Description''' =||= '''Value Format''' =||= '''Default Value''' =|| || {{{width}}} || Line width || ''Width'' || - || || {{{color}}} || Line color || ''Color'' || value of {{{fill-color}}} or (if unset) JOSM's default untagged color ({{{#808080}}}) || || {{{opacity}}} || How transparent the line is. || ''Opacity'' || 1.0 || || {{{dashes}}} || An array of alternating on/off lengths || list of numbers, e.g. [[br]]> 15, 5 [[br]][[br]]may be written as expression: [[br]] > {{{list(3, 4, 5, 6)}}} [[br]][[br]]or the keyword {{{none}}}[[br]]to turn dashes off || - || || {{{dashes-offset}}} || shift the dash pattern by a certain amount || ''Number'' (>= 0) || 0 || || {{{dashes-background-color}}} || The color to use in between the dashes (optional) || ''Color'' || - || || {{{dashes-background-opacity}}} || Opacity value for the dashes background || ''Opacity'' || value of {{{opacity}}} || || {{{linecap}}} || Shape at the end of the line (see [https://www.w3.org/TR/SVG/painting.html#StrokeLinecapProperty here]) || {{{none}}}, {{{round}}}, {{{square}}} || {{{none}}} || || {{{linejoin}}} || Shape at the line corners || {{{round}}}, {{{miter}}}, {{{bevel}}} || {{{round}}} || || {{{miterlimit}}} || Applies for {{{linejoin: miter}}}. Sets the maximum overshoot when line segments meet at a very small angle || ''Number'' (>= 1.0) || 10.0 || || {{{offset}}} || Move line to the left or right (when looking in way direction). This could be used to draw multiple lanes for one way or mark left and right side of a way differently. || ''Number'' (positive value moves line to the left, negative to the right) || 0 || || {{{text-position}}} || set to {{{line}}}, if text should be drawn along the line || {{{line}}}, {{{center}}} || - || || {{{text-...}}}, {{{font-...}}} |||||| general text & font properties || || `repeat-image` || repeated image along a line ''[since 5801]'' || ''Image'' || - || || `repeat-image-width` || Width of the image (optional, see `icon-width`) ''[since 5811]'' || ''Number'' || - || || `repeat-image-height` || Height of the image (optional) ''[since 5811]'' || ''Number'' || - || || `repeat-image-align` || Alignment of the image. Top-, bottom edge or the (horizontal) center line of the image will be along the line ''[since 5801]'' || `top`, `center`, `bottom` || `center` || || `repeat-image-offset` || Offset from the line ''[since 5801]'' || ''Number'' || 0 || || `repeat-image-spacing` || Spacing between repeated images ''[since 5801]'' || ''Number'' || 0 || || `repeat-image-phase` || Initial spacing at the beginning of the line ''[since 5812]'' || ''Number'' || 0 || All these properties (except for {{{text-...}}} and {{{font-...}}}) exist also with the {{{casing-}}} prefix. The casing is a second independent line element, that is drawn below the normal line and can be used to draw a thin frame around the line in another color. ||= '''Key''' =||= '''Description''' =||= '''Value Format''' =||= '''Default Value''' =|| || {{{casing-width}}} || Width of the border on both sides of the main line. In JOSM < 5214: Total width of the casing || ''Width'' (revers to {{{width}}} if relative width is specified) || - || || {{{casing-color}}} || Casing color || ''Color'' || value of {{{fill-color}}} or (if unset) JOSM's default untagged color ({{{#808080}}}) || || {{{casing-opacity}}} || How transparent the casing is. || ''Opacity'' || 1.0 || || {{{casing-}}}... || ... || ... || ... || Similar to {{{casing-}}}, there is also the {{{left-casing-}}} and {{{right-casing-}}} prefix. It draws additional lines to the left and to the right of the main line. === Area styles === ||= '''Key''' =||= '''Description''' =||= '''Value Format''' =||= '''Default Value''' =|| || {{{fill-color}}} || Color in which to fill the area. Until 11700, the alpha component was set to 50 to create a transparency effect. || ''Color'' || - || || {{{fill-image}}} || Image pattern || ''Image'' || - || || {{{fill-extent}}} || Set this property, to draw only the outline of the area. The number specifies, how far to fill from the border of the area towards the center. (If unset, the area will be filled completely) ''[since 9008]'' || ''Number'' || - || || {{{fill-opacity}}} || How transparent the fill is; applies to both color and image || ''Opacity'' || 0.2 ''[since 11700, 1.0 before that]'' (can be changed with the {{{mappaint.fillalpha}}} and {{{mappaint.fill-image-alpha}}} preferences) || || {{{text-position}}} || set to {{{center}}}, if text should be drawn in the center of the area. Set to {{{inside}}} to place the text completely inside the area (since r11722). || {{{line}}}, {{{center}}}, {{{inside}}} || - || || {{{text-...}}}, {{{font-...}}} |||||| general text & font properties || Required properties to create an Area style: {{{fill-color}}} or {{{fill-image}}} === Text & Font properties === {{{#!th align=left valign=top '''Key''' }}} {{{#!th align=left valign=top '''Description''' }}} {{{#!th align=left valign=top '''Value Format''' }}} {{{#!th align=left valign=top '''Default Value''' }}} |------------------------------------------------------------------------------- {{{#!td align=left valign=top {{{text}}} }}} {{{#!td align=left valign=top How to find the label text. No label is displayed, unless this instruction is present. }}} {{{#!td align=left valign=top {{{auto}}} Derive the text automatically. The default name tags are: "{{{name:}}}"+'''', "{{{name}}}", "{{{int_name}}}", "{{{ref}}}", "{{{operator}}}", "{{{brand}}}" and "{{{addr:housenumber}}}". Configure a list of tag names in the preference "{{{mappaint.nameOrder}}}" in order to change this list. (After changing the list, a restart of JOSM is required.) ''String'' Denotes the key of the tag whose value is used as text. ''Expressions'' You can enter an expression to compute the text to be displayed. Examples: * {{{eval("this is a static text")}}} - renderes a static text * {{{eval(concat(tag("first"), "-", tag("second")))}}} - displays the concatenated tags "first" and "second" {{{""}}} To delete a previous set text. }}} {{{#!td align=center valign=top - }}} |------------------------------------------------------------------------------- || {{{text-color}}} || the text color || ''Color'' || {{{white}}} for lines and nodes, {{{#c0c0c0}}} for areas (JOSM "{{{text}}}" and "{{{areatext}}}" color preferences) || || {{{text-opacity}}} || how transparent the text is || ''Opacity'' || 1.0 || || {{{text-offset-x}}} || shift the text horizontally, (not supported for text along line) || ''Number'' || 0 || || {{{text-offset-y}}} (can also be written as {{{text-offset}}}) || shift the text vertically, positive values shift the text in upwards direction || ''Number'' || 0 || || {{{text-halo-radius}}} || size of text background border (to make text visible on background with a similar color) || ''Number'' || - || || {{{text-halo-color}}} || color of the text halo || ''Color'' || complement of the text color || || {{{text-halo-opacity}}} || transparency for the text halo || ''Opacity'' || 1.0 || || {{{font-family}}} || font family || ''String'' || "Helvetica"[[br]](JOSM preference "mappaint.font") || || {{{font-size}}} || font size || ''Number'' || 8[[br]](JOSM preference "mappaint.fontsize") || || {{{font-weight}}} || bold or not || {{{bold}}}, {{{normal}}} || {{{normal}}} || || {{{font-style}}} || italic or not || {{{italic}}}, {{{normal}}} || {{{normal}}} || '' '''Width''' '' - 14.0 (any positive number) - {{{default}}} (use JOSM's default line width, which is 2, but can be configured) - {{{thinnest}}} (draws the line as thin as possible) - +3 (with plus sign in front) adds the amount to the width on the default layer. This applies only for styles that are not on the default layer, e.g. highlights. Another way to write this would be {{{prop("width","default")+3}}}. For {{{casing-width}}}, this refers to the {{{width}}} value on the same layer. '' '''Image''' '' See [wiki:Help/Styles/Images]. '' '''Color''' '' * named color as found in [https://www.w3.org/TR/css3-color/#svg-color this] list * html style: '''{{{#RRGGBB}}}''', '''{{{#RGB}}}''', '''{{{#RRGGBBAA}}}''' * '''{{{rgb(/*r*/, /*g*/, /*b*/)}}}''' - rgb value with arguments from 0.0 to 1.0 * '''{{{rgba(/*r*/, /*g*/, /*b*/, /*alpha*/)}}}''' - rgb value with alpha * '''{{{hsb_color(/*hue*/, /*saturation*/, /*brightness*/)}}}''' - color from HSB color space '' '''Opacity''' '' * from 0.0 (transparent) to 1.0 (opaque) '' '''String''' '' * any character sequence, in quotes, e.g. {{{"images/fill.png"}}}. If the string is an identifier, quotes are optional. (Quote and backslash sign can be escaped.) '' '''Number''' '' * integer or floating point (in simple form e.g. 0.3). In general can be negative, but most properties do not support negative numbers * has a special meaning if you put a "+" sign in front (relative width) == Eval expressions == See [/doc/org/openstreetmap/josm/gui/mappaint/mapcss/ExpressionFactory.Functions.html#method_summary Javadoc of Functions] for the up-to-date list of functions supported by JOSM's MapCSS implementation. +, -, *, /:: arithmetic operations ||, &&, !:: boolean operations <, >, <=, >=, ==:: comparison operators asin, atan, atan2, ceil, cos, cosh, exp, floor, log, max, min, random, round, signum, sin, sinh, sqrt, tan, tanh:: the usual meaning, [https://download.oracle.com/javase/8/docs/api/java/lang/Math.html details] cond(b, fst, snd):: b ? fst : snd:: if ('''b''') then '''fst''' else '''snd''' list(a, b, ...):: create list of values, e.g. for the {{{dashes}}} property get(lst, n):: get the ''n''th element of the list ''lst'' (counting starts at 0) [''since 5699''] split(sep, str):: splits string ''str'' at occurrences of the separator string ''sep'', returns a list [''since 5699''] prop(''p_name''):: value of the property ''p_name'' of the current layer, e.g. prop({{{"width"}}}) prop(''p_name'', ''layer_name''):: property from the layer ''layer_name'' is_prop_set(''p_name''):: true, if property ''p_name'' is set for the current layer is_prop_set(''p_name'', ''layer_name''):: true, if property ''p_name'' is set for the layer ''layer_name'' tag(''key_name''):: get the value of the key ''key_name'' from the object in question parent_tag(''key_name''):: get the value of the key ''key_name'' from the object's parent parent_tags(''key_name''):: returns all parent's values for the key ''key_name'' as a list ordered by a natural ordering [''since 8775''] has_tag_key(''key_name''):: true, if the object has a tag with the given key rgb(''r'', ''g'', ''b''):: create color value (arguments from 0.0 to 1.0) hsb_color(''h'', ''s'', ''b''):: create color from hue, saturation and brightness (arguments from 0.0 to 1.0) [''since 6899''] red(''clr''), green(''clr''), blue(''clr''):: get value of color channels in rgb color model alpha(''clr''):: get the alpha value of the given color [''since 6749''] length(''str''):: length of a string count(''lst''):: length of a list, i.e., counts its elements [''since 7162''] length(''lst''):: length of a list [''since 5699''] – deprecated ''since 7162'' any(obj1, obj2, ...):: returns the first object which is not null (formerly coalesce, [''since 7164'']) concat(''str1'', ''str2'', ...):: assemble the strings to one join(''sep'', ''str1'', ''str2'', ...):: join strings, whith ''sep'' as separator [''since 6737''] join_list(''sep'', ''list_name''):: joins the elements of the list ''list_name'' to one string separated by the separator ''sep'' [''since 8775''] upper(''str''):: converts string to upper case [''since 11756''] lower(''str''):: converts string to lower case [''since 11756''] trim(''str''):: remove leading and trailing whitespace from string [''since 11756''] JOSM_search("..."):: true, if JOSM search applies to the object tr(str, arg0, arg1, ...):: translate from English to the current language (only for strings in the JOSM user interface) [''since 6506''] regexp_test(regexp, string):: test if ''string'' matches pattern ''regexp'' [''since 5699''] regexp_test(regexp, string, flags):: test if ''string'' matches pattern ''regexp''; flags is a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all") [''since 5699''] regexp_match(regexp, string):: Tries to match ''string'' against pattern ''regexp''. Returns a list of capture groups in case of success. The first element (index 0) is the complete match (i.e. ''string''). Further elements correspond to the bracketed parts of the regular expression. [''since 5701''] regexp_match(regexp, string, flags):: Tries to match ''string'' against pattern ''regexp''. Returns a list of capture groups in case of success. The first element (index 0) is the complete match (i.e. ''string''). Further elements correspond to the bracketed parts of the regular expression. Flags is a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all") [''since 5701''] substring(str, idx):: return the substring of ''str'', starting at index ''idx'' (0-indexed) [''since 6534''] substring(str, start, end):: return the substring of ''str'', starting at index ''start'' (inclusive) up to ''end'' (exclusive) (0-indexed) [''since 6534''] replace(string, old, new):: Replaces any occurrence of the substring ''old'' within the string ''string'' with the text ''new'' osm_id():: returns the OSM id of the current object [''since 5699''] parent_osm_id():: returns the OSM id of the object's parent (matched by child selector) [''since 13094''] URL_encode(str):: [https://en.wikipedia.org/wiki/Percent-encoding percent-encode] a string. May be useful for data URLs [''since 6805''] URL_decode(str):: [https://en.wikipedia.org/wiki/Percent-encoding percent-decode] a string. [''since 11756''] XML_encode(str):: escape special characters in xml. E.g. {{{<}}} becomes {{{<}}}, other special characters: {{{>}}}, {{{"}}}, {{{'}}}, {{{&}}}, {{{\n}}}, {{{\t}}} and {{{\r}}} [''since 6809''] CRC32_checksum(''str''):: calculate the CRC32 checksum of a string (result is an integer from 0 to 2^32^-1) [''since 6908''] is_right_hand_traffic():: Check if there is left-hand or right-hand traffic at the current location. [''since 7193''] number_of_tags():: returns the number of tags for the current OSM object [''since 7237''] print(o):: prints a string representation of `o` to the command line (for debugging) [''since 7237''] println(o):: prints a string representation of `o` to the command line, followed by a new line (for debugging) [''since 7237''] JOSM_pref(''key'', ''default''):: Get value from the JOSM advanced preferences. This way you can offer certain options to the user and make the style customizable. It works with strings, numbers, colors and boolean values. [[br]][This function exists since version 3856, but with some restrictions. `JOSM_pref` always returns a string, but in version 7237 and earlier, the automatic conversion of string to boolean and color was not working. You can use the following workarounds for boolean values and color in version 7237 and earlier: `cond(JOSM_pref("myprefkey", "true")="true", "X", "O")` and `html2color(JOSM_pref("mycolor", "#FF345611"))`. These explicit conversions should be no longer necessary in version 7238 and later. Automatic conversion to a number works in any version.] setting():: to use a [[Help/Styles/MapCSSImplementation#Stylesettings|style setting]] [''since 7450''] degree_to_radians():: returns a in degree given direction in radians [''since 8260''] cardinal_to_radians():: returns a cardinal direction in radians [''since 8260''] waylength():: returns the length of the way in metres [''since 8253''] areasize():: returns the area of a closed way in square meters [''since 8253''] at(lat,lon):: returns true if the object centroid lies at given ''lat''/''lon'' coordinates, e.g. to check for nodes at "null island" `node[at(0.0,0.0)]` [''since 12514''] === Examples === * circle symbol for house number with size depending of the number of digits {{{ #!mapcss node[addr:housenumber] { symbol-shape: circle; symbol-size: eval((min(length(tag("addr:housenumber")), 3) * 5) + 3); symbol-fill-color: #B0E0E6; text: "addr:housenumber"; text-anchor-horizontal: center; text-anchor-vertical: center; text-offset-x: -1; text-offset-y: -1; } node[addr:housenumber]::hn_casing { z-index: -100; symbol-shape: circle; symbol-size: +2; symbol-fill-color: blue; } }}} * invert colors {{{ #!mapcss *::* { color: eval(rgb(1 - red(prop(color)), 1 - green(prop(color)), 1 - blue(prop(color)))); fill-color: eval(rgb(1 - red(prop(fill-color)), 1 - green(prop(fill-color)), 1 - blue(prop(fill-color)))); } }}} * random stuff {{{ #!mapcss way { width: eval(random() * 20); color: eval(rgb(random(), random(), random())); } }}} * regexp matching example: change "nameXXXsubname" to "name::subname" {{{ #!mapcss *[name=~/.+XXX.+/] { _match: regexp_match("(.+?)XXX(.+)", tag("name")); text: concat(get(prop("_match"),1), "::", get(prop("_match"),2)); } }}} * paint buildings in different colors according to street in the address tags {{{ #!mapcss area[building][addr:street] { fill-color: hsb_color(CRC32_checksum(tag("addr:street"))/4294967296.0, 0.9, 0.7); fill-opacity: 0.8; } }}} == Compatibility notes == === MapCSS 0.2 === ==== Grammar ==== * {{{way[oneway=yes]}}} does not have any magic, you can use {{{way[oneway?]}}} instead * no {{{@import}}} * JOSM does not require {{{eval(...)}}} to be wrapped around expressions, but for compatibility with other MapCSS implementations you should write it out. ==== Properties ==== At the moment, JOSM does ''not'' support the following properties: line: :: {{{image}}} label: :: {{{font-variant, text-decoration, text-transform, max-width}}} shield: :: not supported === Halcyon (Potlatch 2) === * Text label is placed in the center of the icon. For compatibility with Halcyon put {{{ #!mapcss node { text-anchor-vertical: center; text-anchor-horizontal: center; } }}} at the beginning of your style sheet. * standard z-index in Halcyon is 5, but it is 0 in JOSM * '''{{{image: circle;}}}''' corresponds to '''{{{symbol-shape: circle;}}}''' === Kothic === * Kothic has support for eval, which probably differs from JOSM's eval. * Kothic understands units, whereas JOSM always calculates in pixel. * The extrusion features are not available in JOSM === Ceyx === * seems to have {{{[tunnel=1]}}} instead of {{{[tunnel=yes]}}} (Halcyon) or {{{[tunnel?]}}} (JOSM) == Media queries [''since 6970''] (deprecated) == {{{#!td style="background-color: #faa" Note: media queries are deprecated. You should use @supports rules instead (see above). }}} Media queries are used to skip a section of the style under certain conditions. Typically you want to use a feature which is introduced in a newer version of JOSM, but like to have a fall back style for users of older JOSM clients. Example: {{{ #!mapcss @media (min-josm-version: 9789) { way[highway] { width: 4; color: orange; } /* fancy new stuff */ /* ... */ } @media (max-josm-version: 9788) { way[highway] { width: 4; color: blue; } /* fall back mode, using more simple features */ /* ... */ } }}} The syntax closely matches the official [https://www.w3.org/TR/css3-mediaqueries/#syntax css syntax]. The following conditions are supported: {{{#!th '''Media condition''' }}} {{{#!th '''Description''' }}} |- {{{#!td (min-josm-version: '''') }}} {{{#!td Only include {{{@media}}} section when the current version of JOSM is greater than or equal to the specified number. }}} |- {{{#!td (max-josm-version: '''') }}} {{{#!td Only include {{{@media}}} section when the current version of JOSM is lower than or equal to the specified number. }}} |- {{{#!td (user-agent: '''') }}} {{{#!td Only include {{{@media}}} section when the name of the editor / renderer matches the given string. In JOSM, the only accepted value is {{{josm}}}. }}} Conditions can be combined with {{{and}}}: {{{ #!mapcss @media (min-josm-version: 6970) and (max-josm-version: 7014) { /* only for JOSM versions 6970 to 7014 */ } }}} Multiple combined conditions can be chained with a comma (logical ''or''): {{{ #!mapcss @media (min-josm-version: 6970) and (max-josm-version: 7014), (user-agent: myEditor) { /* for JOSM version 6970 to 7014 and for the editor called "myEditor" */ } }}} Since media queries are only supported in JOSM 6970 and later, you should also specify this as minimum JOSM version in the meta selector: {{{ #!mapcss meta { min-josm-version: "6970"; /* This style uses media queries */ /* ... */ } }}} {{{#!comment There is also the {{{not}}} keyword (see the linked css doc for details). This is implemented, but probably not very useful. Feel free to add documentation. }}}