Skip to content

Invisible hover layer

Daniel Imfeld edited this page Nov 6, 2023 · 2 revisions

This is a nice pattern when you want a map with hover behavior on thin map lines. Draw the lines in one layer, then place another layer over it with the same data, but thicker lines and zero opacity. This makes it much easier to place the mouse cursor over the desired line.

  <MapLibre {bounds} style="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json">
    <GeoJSON data={geojson}>
      <LineLayer
        id="trip-line"
        layout={{
          'line-cap': 'round',
        }}
        paint={{
          'line-color': ['get', 'color'],
          'line-width': 3,
        }}
      ></LineLayer>
      <!-- An invisible, wider layer that overlays the top one to make hovering easier. -->
      <LineLayer
        id="popup-catcher"
        layout={{
          'line-cap': 'round',
        }}
        paint={{
          'line-opacity': 0,
          'line-width': 10,
        }}
      >
        <Popup openOn="hover" let:features>
          {@const props = features[0].properties}
          <div class="bg-white">
            <p>{props.label}</p>
            <p>{props.distance} mi</p>
          </div>
        </Popup>
      </LineLayer>
    </GeoJSON>
  </MapLibre>
Clone this wiki locally