Leo Sonnekus
Leo Sonnekus

Reputation: 31

How to add hover effect to new layer created with custom geojson

I've built a map and added a layer that highlights a specific neighborhood, I'd like to add a hover effect to the layer. just like in this example https://docs.mapbox.com/mapbox-gl-js/example/hover-styles

I got as far as creating my own layer with the geojson but the example I am trying to follow uses an external data source whereas I am using my own. I tried to reference my data but I don't think I am doing it correctly. Pleases see this link with a working version showing the layer highlighting the neighborhood.

This is the link to what I have so far https://jsfiddle.net/jrax4pvm/1/

Here's my JS

mapboxgl.accessToken = 

'pk.eyJ1IjoibGVvc29ubmVrdXM5NSIsImEiOiJjazAxdHcyZWExMHBjM2lwN2psMDhheXQwIn0.KpEYrurG0lE55PLKMuYtKw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/leosonnekus95/ck11gbbaz0neb1cmrunqmijkf',
zoom: 15,
center: [174.7570008, -36.8658221]
});

map.on('load', function () {



           'id': 'Uptown',
                    'type': 'fill',
                    'source': {
                    'type': 'geojson',
                    'data': {
                    'type': 'Feature',
                    'geometry': {
                    'type': 'Polygon',
                    'coordinates': 


                    [
        [ /* Co-ordinates here..*/ ]]

       }
                    }
                    },
                    'layout': {},
                    'paint': {
                    'fill-color': '#088',
                    'fill-opacity': 0.8
                    }
                    });


    });

I'd really like to make this layer hoverable/clickable and suspect I have to create a combined version of these two examples

https://docs.mapbox.com/mapbox-gl-js/example/geojson-polygon/ https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/

and would like some guidance.

Upvotes: 3

Views: 2412

Answers (1)

Patrick Leonard
Patrick Leonard

Reputation: 412

You'll want to add map.on('mouseenter') and map.on('mouseleave') functions which target your layer to your code like this:

map.on('mouseenter', 'Uptown', function(e) {
  map.setPaintProperty('Uptown', 'fill-color', '#FF0000');
});

map.on('mouseleave', 'Uptown', function() {
  map.setPaintProperty('Uptown', 'fill-color', '#1F06F0'));
}); 

I've updated your code in another JSFiddle (https://jsfiddle.net/pjleonard37/jfd0bsha/) with these changes.

Disclaimer: I work at Mapbox

Upvotes: 1

Related Questions