Текстовые метки | MapGL | 2GIS Documentation
MapGL JS API

Текстовые метки

Чтобы добавить текстовую метку на карту, нужно указать ее координаты и текст:

const label = new mapgl.Label(map, {
    coordinates: [55.31878, 25.23584],
    text: 'Your label text',
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="A single label example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            const label = new mapgl.Label(map, {
                coordinates: [55.31878, 25.23584],
                text: 'Your label text',
            });
        </script>
    </body>
</html>

На карту можно добавить несколько текстовых меток:

const firstLabel = new mapgl.Label(map, {
    coordinates: [55.27414, 25.25757],
    text: 'First label',
});
const secondLabel = new mapgl.Label(map, {
    coordinates: [55.28925, 25.21161],
    text: 'Second label',
});
const thirdLabel = new mapgl.Label(map, {
    coordinates: [55.34418, 25.21534],
    text: 'Third label',
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="A several labels example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 12,
                key: 'Your API access key',
            });
            const firstLabel = new mapgl.Label(map, {
                coordinates: [55.27414, 25.25757],
                text: 'First label',
            });
            const secondLabel = new mapgl.Label(map, {
                coordinates: [55.28925, 25.21161],
                text: 'Second label',
            });
            const thirdLabel = new mapgl.Label(map, {
                coordinates: [55.34418, 25.21534],
                text: 'Third label',
            });
        </script>
    </body>
</html>

Чтобы использовать многострочный текст в метках, строки нужно разделить символом \n:

const label = new mapgl.Label(map, {
    coordinates: [55.31878, 25.23584],
    text: 'First line\nSecond line\nThird line',
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="A multiline label example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            const label = new mapgl.Label(map, {
                coordinates: [55.31878, 25.23584],
                text: 'First line\nSecond line\nThird line',
            });
        </script>
    </body>
</html>

По умолчанию текст центрируется относительно указанных координат. Чтобы изменить расположение текста, нужно указать параметры relativeAnchor и offset (см. LabelOptions для подробного описания):

// Горизонтальный и вертикальный центр (расположение по умолчанию)
const defaultPlacement = new mapgl.Label(map, {
    coordinates: [55.32878, 25.23584],
    text: 'Default label placement',
});
// Выравнивание справа по центру
const rightCenterPlacement = new mapgl.Label(map, {
    coordinates: [55.32878, 25.24584],
    text: 'Right center placement',
    relativeAnchor: [0, 0.5],
});
// Выравнивание по левому верхнему краю с отступом
const leftTopPlacement = new mapgl.Label(map, {
    coordinates: [55.30878, 25.22584],
    text: 'Left top placement and offset',
    offset: [-10, -10],
    relativeAnchor: [1, 1],
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            // The center center label placement, by default.
            const defaultPlacement = new mapgl.Label(map, {
                coordinates: [55.32878, 25.23584],
                text: 'Default label placement',
            });
            // The right center label placement.
            const rightCenterPlacement = new mapgl.Label(map, {
                coordinates: [55.32878, 25.24584],
                text: 'Right center placement',
                relativeAnchor: [0, 0.5],
            });
            // The left top label placement with offset.
            const leftTopPlacement = new mapgl.Label(map, {
                coordinates: [55.30878, 25.22584],
                text: 'Left top placement and offset',
                offset: [-10, -10],
                relativeAnchor: [1, 1],
            });

            // The markers below are only for visualizing the geo-coordinates of the labels.
            // You don't need them in common.
            const defaultPlacementAnchor = new mapgl.Marker(map, {
                coordinates: [55.32878, 25.23584],
                icon: 'https://docs.2gis.com/img/mapgl/anchor.svg',
                zIndex: 100,
            });
            const rightCenterPlacementAnchor = new mapgl.Marker(map, {
                coordinates: [55.32878, 25.24584],
                icon: 'https://docs.2gis.com/img/mapgl/anchor.svg',
                zIndex: 100,
            });
            const leftTopPlacementAnchor = new mapgl.Marker(map, {
                coordinates: [55.30878, 25.22584],
                icon: 'https://docs.2gis.com/img/mapgl/anchor.svg',
                zIndex: 100,
            });
        </script>
    </body>
</html>

Чтобы добавить обводку для текста, нужно указать параметры haloColor (цвет обводки) и haloRadius (толщина обводки):

const label = new mapgl.Label(map, {
    coordinates: [55.27414, 25.25757],
    text: 'First label',
    color: '#0000ff',
    haloRadius: 2,
    haloColor: '#00ff0055',
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="A label with halo example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            const label = new mapgl.Label(map, {
                coordinates: [55.31878, 25.23584],
                text: 'Label with halo',
                color: '#0000ff',
                haloRadius: 2,
                haloColor: '#00ff0055',
            });
        </script>
    </body>
</html>

Чтобы добавить фоновое изображение для текста, нужно указать параметр image. Для фонового изображения можно ограничить области, которые будут растягиваться под размер текста. Для этого используются параметры stretchX (разрешено растягивание по горизонтали) и stretchY (разрешено растягивание по вертикали).

tooltip-big-plot.svg

const label = new mapgl.Label(map, {
    coordinates: [55.31878, 25.23584],
    text: 'Label with image',
    fontSize: 64,
    image: {
        url: 'https://docs.2gis.com/img/mapgl/tooltip-big.svg',
        size: [500, 250],
        // Области изображения, которые будут растягиваться горизонтально (синие)
        stretchX: [
            [50, 200], // пиксели между X=50 и X=200 (50 ≤ X ≤ 200)
            [300, 450], // пиксели между X=300 и X=450 (300 ≤ X ≤ 450)
        ],
        // Области изображения, которые будут растягиваться вертикально (красные)
        stretchY: [
            [50, 150], // пиксели между Y=50 и Y=150 (50 ≤ Y ≤ 150)
        ],
        // Отступы вокруг текста (как в CSS)
        padding: [50, 50, 100, 50],
    },
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="A label with background image example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            const label = new mapgl.Label(map, {
                coordinates: [55.31878, 25.23884],
                text: 'Label with image',
                fontSize: 64,
                image: {
                    url: 'https://docs.2gis.com/img/mapgl/tooltip-big.svg',
                    size: [500, 250],
                    // The two (blue) columns of pixels that can be stretched horizontally:
                    //   - the pixels between x: 50 and x: 200 can be stretched
                    //   - the pixels between x: 300 and x: 450 can be stretched.
                    stretchX: [
                        [50, 200],
                        [300, 450],
                    ],
                    // The one (red) row of pixels that can be stretched vertically:
                    //   - the pixels between y: 50 and y: 150 can be stretched
                    stretchY: [[50, 150]],
                    // padding like in CSS [top, right, bottom, left]:
                    padding: [50, 50, 100, 50],
                },
            });
        </script>
    </body>
</html>

Чтобы корректно отобразить на карте несколько текстовых меток с фоновыми изображениями, важно указать для каждой метки параметр zIndex с уникальным значением:

const bottomLabel = new mapgl.Label(map, {
    ...
    zIndex: 1
});
const middleLabel = new mapgl.Label(map, {
    ...
    zIndex: 2
});
const topLabel = new mapgl.Label(map, {
    ...
    zIndex: 3
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Map API</title>
        <meta name="description" content="Several labels with background image example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const map = new mapgl.Map('container', {
                center: [55.31878, 25.23584],
                zoom: 13,
                key: 'Your API access key',
            });
            const bottomLabel = new mapgl.Label(map, {
                coordinates: [55.27878, 25.23884],
                text: 'Label with image',
                zIndex: 1,
                image: {
                    url: 'https://docs.2gis.com/img/mapgl/tooltip.svg',
                    size: [100, 50],
                    stretchX: [
                        [10, 30],
                        [70, 90],
                    ],
                    stretchY: [[10, 30]],
                    padding: [10, 10, 20, 10],
                },
            });
            const middleLabel = new mapgl.Label(map, {
                coordinates: [55.31878, 25.23584],
                text: 'First line\nSecond line\nThird line',
                zIndex: 2,
                image: {
                    url: 'https://docs.2gis.com/img/mapgl/tooltip@2x.png',
                    pixelRatio: 2,
                    size: [100, 50],
                    stretchX: [
                        [10, 30],
                        [70, 90],
                    ],
                    stretchY: [[10, 30]],
                    padding: [10, 10, 20, 10],
                },
            });
            const topLabel = new mapgl.Label(map, {
                coordinates: [55.36878, 25.23084],
                text: 'Label with debug image',
                zIndex: 3,
                image: {
                    url: 'https://docs.2gis.com/img/mapgl/tooltip-debug.svg',
                    size: [100, 50],
                    stretchX: [
                        [10, 30],
                        [70, 90],
                    ],
                    stretchY: [[10, 30]],
                    padding: [10, 10, 20, 10],
                },
            });
        </script>
    </body>
</html>