Skip to main content

Labels

Simple label

To add a Label to the map, specify the coordinates and text:

const label = new mapgl.Label(map, {
coordinates: [37.615655, 55.768005],
text: 'Label text',
});

Multiple labels

You can add multiple Labels to the map:

const firstLabel = new mapgl.Label(map, {
coordinates: [37.577620, 55.778375],
text: 'First label',
});
const secondLabel = new mapgl.Label(map, {
coordinates: [37.608676, 55.766095],
text: 'Second label',
});
const thirdLabel = new mapgl.Label(map, {
coordinates: [37.650029, 55.773766],
text: 'Third label',
});

Multiline label

To add a Label with multiple lines of text, use the newline character (\n) as a line break:

const label = new mapgl.Label(map, {
coordinates: [37.615655, 55.768005],
text: 'First line\nSecond line\nThird line',
});

Text alignment

By default, the text is centered on the specified coordinates. To change the alignment of the text, use the relativeAnchor and offset parameters (see LabelOptions for more details):

// Horizontal and vertical center (the default)
const defaultPlacement = new mapgl.Label(map, {
coordinates: [37.577620, 55.778375],
text: 'Default label alignment',
});
// Right-center alignment
const rightCenterPlacement = new mapgl.Label(map, {
coordinates: [37.608676, 55.766095],
text: 'Right-center alignment',
relativeAnchor: [0, 0.5],
});
// Top-left alignment with an offset
const leftTopPlacement = new mapgl.Label(map, {
coordinates: [37.660029, 55.773766],
text: 'Top-left alignment with offset',
offset: [-10, -10],
relativeAnchor: [1, 1],
});

Text outline

To add an outline effect, use the haloColor (outline color) and haloRadius (outline width) parameters:

const label = new mapgl.Label(map, {
coordinates: [37.615655, 55.768005],
text: 'Text outline',
color: '#0000ff',
haloRadius: 2,
haloColor: '#00ff0055',
});

Background image

You can use a stretchable image as a text background. To do that, use the image parameter and define the stretchable areas by using the stretchX (stretchable horizontally) and stretchY (stretchable vertically) parameters:

tooltip-big-plot.svg

const label = new mapgl.Label(map, {
coordinates: [37.615655, 55.768005],
text: 'Label with image',
fontSize: 64,
image: {
url: 'https://docs.2gis.com/img/mapgl/tooltip-big.svg',
size: [500, 250],
// Areas that can be stretched horizontally (blue)
stretchX: [
[50, 200], // all pixels where X ≥ 50 and X ≤ 200
[300, 450], // all pixels where X ≥ 300 and X ≤ 450
],
// Areas that can be stretched vertically (red)
stretchY: [
[50, 150], // all pixels where Y ≥ 50 and Y ≤ 150
],
// CSS-like padding for text
padding: [50, 50, 100, 50],
},
});

If you use multiple Labels with background images, it is important to set different zIndex for each Label so that the images can be correctly overlapped:

const bottomLabel = new mapgl.Label(map, {
...
zIndex: 1
});
const middleLabel = new mapgl.Label(map, {
...
zIndex: 2
});
const topLabel = new mapgl.Label(map, {
...
zIndex: 3
});