Custom button layout
Object layouts can be created using the templateLayoutFactory factory and text templates.
This example creates a custom layout for a button. The layout of the control is based on its data, status, and options.
The layout is automatically adjusted when changes are made to the values of fields, states, or options that are used in its text template.
index.html
button_layout.js
<!DOCTYPE html>
<html>
<head>
<title>Examples. Custom layout for a button.</title>
<meta
http-equiv="Content-Type"
content="text/html; charset=UTF-8"
/>
<!--
Set your own API-key. Testing key is not valid for other web-sites and services.
Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
-->
<script
src="https://api-maps.yandex.ru/2.1/?lang=en_RU&apikey=<your API-key>"
type="text/javascript"
></script>
<script src="button_layout.js" type="text/javascript"></script>
<style>
html,
body,
#map {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.my-button {
display: inline-block;
padding: 3px 5px;
background: #eee;
border: 1px solid #bbb;
border-radius: 3px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.my-button__text {
font-family: "Arial", sans-serif;
font-size: 14px;
color: #333;
margin-left: 10px;
}
.my-button__img {
padding: 0;
margin-bottom: -3px;
}
.my-button_small .my-button__text {
display: none;
}
.my-button_medium .my-button__img {
display: none;
}
.my-button_large .my-button__text {
margin-left: 10px;
}
.my-button-selected {
color: #333333;
background-color: #e6e6e6;
border: 2px dashed #333;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
ymaps.ready(init);
function init() {
var myMap = new ymaps.Map("map", {
center: [55.650625, 37.62708],
zoom: 10,
controls: [],
}),
/**
* The button layout should display the 'data.content' field
* and change depending on whether the button was clicked or not.
* The current size (small, medium, large) is calculated from the value of the 'maxWidth' option
* @see https://api.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.Button.xml#param-parameters
*/
ButtonLayout = ymaps.templateLayoutFactory.createClass(
[
'<div title="{{ data.title }}" class="my-button ',
'{% if state.size == "small" %}my-button_small{% endif %}',
'{% if state.size == "medium" %}my-button_medium{% endif %}',
'{% if state.size == "large" %}my-button_large{% endif %}',
'{% if state.selected %} my-button-selected{% endif %}">',
'<img class="my-button__img" src="{{ data.image }}" alt="{{ data.title }}">',
'<span class="my-button__text">{{ data.content }}</span>',
"</div>",
].join("")
),
button = new ymaps.control.Button({
data: {
content: "Click-click-click",
image: "pen.svg",
title: "Click-click-click",
},
options: {
layout: ButtonLayout,
maxWidth: [170, 190, 220],
},
});
myMap.controls.add(button, {
position: {
right: 5,
top: 5,
},
});
}