maplibre highlight on hover

2 min read 17-10-2024
maplibre highlight on hover

MapLibre is a powerful library for interactive maps, providing users with the ability to create and manage geospatial data effectively. One of the fascinating features of MapLibre is the ability to highlight specific map features when a user hovers over them. This functionality enhances user experience and improves the interactivity of the map. In this article, we'll explore how to implement highlight on hover using MapLibre.

What is MapLibre?

MapLibre is an open-source fork of Mapbox GL JS, designed to enable developers to create customizable maps without licensing restrictions. It supports vector tiles, raster tiles, and provides a host of functionalities to manipulate and display geospatial data.

Why Highlight on Hover?

Highlighting features on hover can serve various purposes:

  • User Engagement: Engaging users by providing immediate feedback on their interactions.
  • Information Display: Showing additional information related to the feature being hovered over.
  • Enhanced Usability: Making it easier for users to identify different features on the map.

Implementing Highlight on Hover

To implement highlighting features on hover, you will follow these steps:

1. Set Up Your Map

First, make sure you have MapLibre integrated into your project. You'll need to set up your HTML and JavaScript files to initialize a basic map.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>MapLibre Highlight on Hover</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css" rel="stylesheet" />
    <style>
        body { margin: 0; padding: 0; }
        #map { width: 100%; height: 100vh; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.js"></script>
    <script>
        const map = new maplibregl.Map({
            container: 'map',
            style: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            center: [0, 0],
            zoom: 2
        });
    </script>
</body>
</html>

2. Add GeoJSON Data

You can add any GeoJSON data that you want to display on the map. For example:

const geojsonData = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [-74.006, 40.7128] // Example coordinates for New York
            },
            properties: {
                title: 'New York'
            }
        }
    ]
};

// Add the GeoJSON layer to the map
map.on('load', () => {
    map.addSource('places', {
        type: 'geojson',
        data: geojsonData
    });

    map.addLayer({
        id: 'places',
        type: 'circle',
        source: 'places',
        paint: {
            'circle-radius': 10,
            'circle-color': '#007cbf'
        }
    });
});

3. Implement Highlight on Hover

You can implement the hover effect by listening to the mouseenter and mouseleave events:

map.on('mouseenter', 'places', (e) => {
    // Change the cursor style
    map.getCanvas().style.cursor = 'pointer';

    // Get the coordinates of the feature
    const coordinates = e.features[0].geometry.coordinates.slice();
    const description = e.features[0].properties.title;

    // Create a popup
    new maplibregl.Popup()
        .setLngLat(coordinates)
        .setHTML(description)
        .addTo(map);

    // Highlight the feature
    map.setPaintProperty('places', 'circle-color', '#ff0000');
});

map.on('mouseleave', 'places', () => {
    // Reset the cursor
    map.getCanvas().style.cursor = '';

    // Remove the popup
    map.closePopup();

    // Reset the highlighting
    map.setPaintProperty('places', 'circle-color', '#007cbf');
});

Summary

In this guide, we covered how to implement a highlight on hover effect using MapLibre. This functionality not only enhances the user experience but also provides a means to display additional information in a clear and engaging way. With these steps, you can create interactive maps that respond to user actions effectively.

Feel free to customize the colors and styles to fit your application's design!

close