Tooltips
To display a tooltip when hovering over an object, create an HTML element and show it or hide it using mouseover and mouseout event handlers.
Tooltip for a marker
For example, to add a tooltip for a marker, add mouseover and mouseout event handlers to the marker using the on() method:
marker.on('mouseover', (e) => {
console.log('Cursor hovers over the marker');
});
marker.on('mouseout', (e) => {
console.log('Cursor leaves the marker');
});
The main idea is to show an HTML element on mouseover and hide it on mouseout. To get the display coordinates for the element, you can use the event argument (see MapPointerEvent).
Do not forget to hide the tooltip initially and set its position to absolute or fixed. Additionally, you need to set the pointer-events property to none or add a small offset to the tooltip. Otherwise, it will be displayed right under the cursor, which will trigger the mouseout event and hide the tooltip.
Simple tooltip may look like this:
<style>
#tooltip {
padding: 20px 40px;
background: #fff;
display: none;
position: fixed;
pointer-events: none;
}
</style>
<div id="tooltip">Tooltip</div>
Example of the code that displays the tooltip when you hover over the marker:
const tooltipEl = document.getElementById('tooltip');
marker.on('mouseover', (event) => {
// Offset in pixels
const offset = 5;
tooltipEl.style.top = (event.point[1] + offset) + 'px';
tooltipEl.style.left = (event.point[0] + offset) + 'px';
tooltipEl.style.display = 'block';
});
marker.on('mouseout', (e) => {
tooltipEl.style.display = 'none';
});
You can find a full example below. Hover the cursor over the marker to see the tooltip.
Tooltip for a geometric shape
You can also set tooltips for other types of objects. For example, to set a tooltip for a Polyline, you can use the same two events that were used in the marker tooltip example (mouseover and mouseout).
You can find a full example below. Hover the cursor over the polyline to see the tooltip.