Tooltips
There is no predefined method to create a tooltip (i.e., an element that shows when the cursor hovers over some other element) in MapGL API. To create a tooltip, you can use mouseover
and mouseout
listeners to display a custom element relative to the coordinates of the required object.
Tooltip for a marker
For example, to set a tooltip for a marker, you can add mouseover
and mouseout
event handlers to the marker:
marker.on('mouseover', (e) => {
console.log('cursor entering the marker');
});
marker.on('mouseout', (e) => {
console.log('cursor leaving 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">Hello, world!</div>
And the code that displays the tooltip may look like this:
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 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.