admin管理员组

文章数量:1391955

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();
    });
}

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();
    });
}
Share Improve this question edited Dec 5, 2019 at 11:21 Nick Parsons 51.2k6 gold badges57 silver badges78 bronze badges asked Dec 5, 2019 at 11:19 MrAndreMrAndre 1,0471 gold badge12 silver badges32 bronze badges 2
  • There's an offset option on a popup which might help – peeebeee Commented Dec 5, 2019 at 12:10
  • You might be interested in using Leaflet tooltip instead. See stackoverflow./questions/39770744/… – ghybs Commented Dec 5, 2019 at 12:57
Add a ment  | 

2 Answers 2

Reset to default 3

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();
    });
}

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) {

本文标签: javascriptLeaflet show popup on hover with the location of the mouseStack Overflow