I have a leaflet map with a LineString.
// a GeoJSON LineString
var geojson = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [[-101.123, 40.2500], [-101.123, 40.2503]]
}
};
// create map and add json
var map = L.map('map');
var geojsonLayer = new L.GeoJSON(geojson).addTo(map);
map.fitBounds(geojsonLayer.getBounds())
// add popup for the line
geojsonLayer.eachLayer(function (layer) {
var popup = L.popup();
popup.setContent('text');
layer.bindPopup(popup);
layer.on('click mouseover', function () {
layer.openPopup();
});
});
When I over it, a popup opens at the LineString center.
How can I make it open over at the cursor position?
Here is a simple working example: http://jsfiddle.net/wuu8Lv2t/1/
Don't let the layer open the popup, instead use openOn(map) setting the position with the coordinates from the event e.latlng
// add popup for the line
geojsonLayer.eachLayer(function (layer) {
var popup = L.popup();
popup.setContent('text');
layer.bindPopup(popup);
layer.on('mouseover', function (e) {
var popup = e.target.getPopup();
popup.setLatLng(e.latlng).openOn(map);
});
layer.on('mouseout', function(e) {
e.target.closePopup();
});
layer.on('mousemove', function (e) {
e.target.closePopup();
var popup = e.target.getPopup();
popup.setLatLng(e.latlng).openOn(map);
});
});
Note that in your question there is a mistake: you can't use the variable layer in the event hander, you have to use e.target (see doc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With