2
votes

I'm having a bit of trouble figuring out why the mouseover event doesn't work with mapbox gl.

map.on('load', function() {
  var geoJson = '{
    "type": "FeatureCollection",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features": [
    {
        "type": "Feature",
        "properties": {
            ...
        },
        "geometry": {
            "type": "Point",
            "coordinates": [
                -118.6059,
                34.1829
            ]
        }
    }]
  }';


  map.addSource('someData', {
    type: 'geojson',
    data: geoJson,
    cluster: true,
    clusterMaxZoom: 14
  });

  map.addLayer({
    'id': 'unclustered-markers',
    'type': 'symbol',
    'source': 'someData',
    'layout': {
        'icon-image': 'circle-11'
    }
  });
});

So that part works and the coordinates are displayed on the map within the cluster. However, when I try the mouseover event, nothing happens.

map.on('mouseover',function(e) {
    console.log(e);                 // nothing is logged when I hover over the map or the points
    var features = map.queryRenderedFeatures(e.point, { layers: ['unclustered-markers'] });
    ...
});

If I change that event to click then the event is logged to the console when I click on the map.

3

3 Answers

0
votes

It seems that you are using the wrong event name. Note that is it mousemove, not mouseover. To fix this, change your code to:

map.on('mousemove',function(e) {
    console.log(e);                 
    //....
});

Here is a working example: https://jsfiddle.net/kmandov/o870ufLr/ Open the console to see the events.

0
votes

GL JS does not fire the mouseover event despite firing mousemove and moseout events. I don't think there is a reason why we do not fire mouseover. We should add this event.

0
votes

There is also mouseenter and should be considered depending on your application. In case you have stumbled upon this question because Mapbox was giving you erratic behavior with missing popups, here is a work around to guarantee the popup will be above the feature the user hovered over.

Use Mapbox to handle the event and get the mouse coordinates like so:

map.on('mouseenter', 'layerID', (event) => {
    var x = event.originalEvent.clientX
    var y = event.originalEvent.clientY

Well then, it's a matter of using your favorite DOM handler and adding a <div> for the popup. Set the position of the popup to where the user hovered like so :

{left : `${x}`, top : `${y}`, position : 'absolute', zIndex : 1}