Labels
Simple label
To add a Label to the map, specify the coordinates
and text
:
const label = new mapgl.Label(map, {
coordinates: [55.31878, 25.23584],
text: 'Your label text',
});
Multiple labels
You can add multiple Labels to the map:
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',
});
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: [55.31878, 25.23584],
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: [55.32878, 25.23584],
text: 'Default label placement',
});
// Middle-right alignment
const rightCenterPlacement = new mapgl.Label(map, {
coordinates: [55.32878, 25.24584],
text: 'Right center placement',
relativeAnchor: [0, 0.5],
});
// Top-left alignment with an offset
const leftTopPlacement = new mapgl.Label(map, {
coordinates: [55.30878, 25.22584],
text: 'Left top placement and 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: [55.27414, 25.25757],
text: 'First label',
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:
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],
// 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
});