Search code examples
javascriptleafletlocation

Leaflet JS Map: Popup on MouseOver opens in incorrect location


I'm using Leaflet jS for a map and it works well except for a requirement to popup the name of the country when hovering over a country on the map.

On using the following code

layer.on({
  mouseover: function over(e) {
    layer.bindPopup(L.popup().setContent(feature.properties.name));
    layer.openPopup();
  },
  mouseout: function out(e) {
    layer.closePopup();
  },
});

The Country name does pop up however it's slightly off in int's location. For example the US when hovered over the popup opens in the Pacific west of Mexico. All popups are slightly off from where the hover has occurred.

Do you know how the popups can be set to popup always directly on the country?

Thanks in advance for any help on this.


Solution

  • While not explicitly documented, when you bindPopup on a Leaflet path (vector) Layer, it will position the popup tip on the Layer "center", i.e. the middle compared to its bounds.

    In your case with USA, the Layer is probably a multipolygon that includes Hawaii. That shifts the Layer bounds far to the South West, leading to a layer "center" off Mexico.

    You could compute a more sensible "center" for your use case, and set the popup position explicitly on map rather than binding it to a Layer (center).

    However you will probably in some cases (typically for small Layers) hit the classic usability issue of blinking mouseover popup: if the popup is open under the mouse, a mouseout event fires, which closes your popup. Then a new mouseover event fires, which opens a new popup, etc.

    The usual workaround is to use a Leaflet Tooltip instead, for which you do not need to implement the mouseover/mouseout stuff yourself. And you can use the sticky option to position it next to the mouse cursor, to get rid of any center computation.

    If true, the tooltip will follow the mouse instead of being fixed at the feature center.