3

I am using leaflet to show my geometry locations on the map. Now I have the popups working fine but when you hover over them, the location of the popup is in the middle of the line/string for example and not on the location of the mouse. Is it possible to change it to the location of the mouse so the map doesn't just suddenly move to a different location?

The code that I am using to open the popups in leaflet is as follows:

function addPopup(feature, layer) {
    var popupContent = feature.properties.name;
    layer.bindPopup(popupContent);

    layer.on('mouseover', function (e) {
        this.openPopup();
    });
    layer.on('mouseout', function (e) {
        this.closePopup();
    });
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
MrAndre
  • 811
  • 1
  • 10
  • 26
  • There's an `offset` option on a popup which might help – peeebeee Dec 05 '19 at 12:10
  • You might be interested in using Leaflet tooltip instead. See https://stackoverflow.com/questions/39770744/how-to-add-a-html-title-tooltip-to-a-leaflet-js-polygon/39770975?r=SearchResults#39770975 – ghybs Dec 05 '19 at 12:57

2 Answers2

2

After @Falke Design pointed out that you could give the latlng coordinates to the openPopup function I made a cleaner version of the code:

function addPopup(feature, layer) {
    var popupContent = feature.properties.name;
    layer.bindPopup(popupContent);

    layer.on('mouseover', function (e) {
        this.openPopup(e.latlng);
    });
    layer.on('mouseout', function (e) {
        this.closePopup();
    });
}
MrAndre
  • 811
  • 1
  • 10
  • 26
1

You can convert the mousepoint to latlng and set the popup there.

layer.on('mouseover', function (e) {
        var p = L.point([e.originalEvent.clientX,e.originalEvent.clientY])
        var latlng = mymap.containerPointToLatLng(p);
        this.openPopup(latlng)
    });
layer.on('mousemove', function(e){
    var p = L.point([e.originalEvent.clientX,e.originalEvent.clientY])
        var latlng = mymap.containerPointToLatLng(p);
        this.openPopup(latlng)
})
    layer.on('mouseout', function (e) {

Falke Design
  • 10,635
  • 3
  • 15
  • 30