cj devin
cj devin

Reputation: 1375

Mapbox gl : On mouse hover on layers change cursor pointer style

I have 10 to 15 different different layers for example car,bus,route etc etc.These layer i am adding dynamic on map when if needed because all the time all layers are does not exist on map.

So i am showing info on single click about layers,but i want when i hover mouse on layer change mouse pointer cursor style to 'crosshair'.

i have written change cursor style on mouseenter event but it seems sometimes working and sometime even though mouse is on hover on layer but cursor style does not get changed.

First way:

 map.on('mouseenter', (e: any) => {
      self.mapInstance.getCanvas().style.cursor = 'crosshair';
    });

Second Way:

      map.on('mouseenter',(e: any) => {         
       var features = map.queryRenderedFeatures(e.point,{ layers: ['Car',"Bus"] });
//error let's say any layer still on exist on map
        if(features.length)
         map.getCanvas().style.cursor = 'crosshair';    
            });

My issues:

  1. Cursor style not getting change

  2. Error on queryRenderedFeatures like layer does not exists

  3. Mouse flickering on hover layer

How to get change style of the cursor on mouse hover on different different layers?

Upvotes: 16

Views: 15323

Answers (2)

vvn050
vvn050

Reputation: 222

 map.on("mouseenter", layer.id, () => {
          map.getCanvas().style.cursor = "pointer";
        });

 map.on("mouseleave", shape.id, () => {
          map.getCanvas().style.cursor = "default";
        });

You can add custom events to each layer, such as clicks. Same goes for mouse events.

Upvotes: 8

Riley Davidson
Riley Davidson

Reputation: 377

map.on('mouseenter', 'clusters', () => {
  map.getCanvas().style.cursor = 'pointer'
})
map.on('mouseleave', 'clusters', () => {
  map.getCanvas().style.cursor = ''
})

This is how to get it working with clusers specifically but the code might still be helpful.

Good luck !

Upvotes: 24

Related Questions