将鼠标悬停在Folium的弹出窗口中

时间:2016-12-12 07:08:10

标签: python folium

用这样一个简单的例子:

import folium

map_1 = folium.Map(location=[45.372, -121.6972], zoom_start=12,
                   tiles='Stamen Terrain')
folium.Marker([45.3288, -121.6625], popup='Mt. Hood Meadows').add_to(map_1)
map_1

只需将鼠标放上即可显示弹出窗口吗? 这对folium有可能吗?

4 个答案:

答案 0 :(得分:2)

你不能轻易地从folium做到这一点。但是由于folium确实创建了LeafletJS代码,您可以修改输出以使其工作。为此,您必须在结果html中添加this answer中所述的代码:

    marker.bindPopup("Popup content");
    marker.on('mouseover', function (e) {
        this.openPopup();
    });
    marker.on('mouseout', function (e) {
        this.closePopup();
    });

如果你有很多标记,这可能会成为一项艰巨的任务,但你可以通过python来完成它(虽然看起来不太漂亮)。伪代码:

import re

with open("map.html") as inf:
    txt = inf.read()

#Find all the markers names given by folium
markers = re.findall(r'\bmarker_\w+', txt)

for marker in markers:
   # Add the code given before to the string txt

# Save the new map
with open("new_map.html", "w") as outf:
    outf.write(txt)

此代码打开生成的html文件,查找所有标记,并为每个标记添加代码。

答案 1 :(得分:2)

更新答案

事实证明,此功能已放入 folium 的代码库中。

只需添加 tooltip 参数,如下所示:

import folium

map_1 = folium.Map(location=[45.372, -121.6972], zoom_start=12, tiles='Stamen Terrain',
                   tooltip = 'This tooltip will appear on hover' # THIS
                  )
folium.Marker([45.3288, -121.6625], popup='Mt. Hood Meadows').add_to(map_1)
map_1

答案 2 :(得分:1)

您的问题是询问 folium ,我不这么认为,但我认为您可以添加一些Javascript(jquery,我认为这非常容易),模拟点击事件onmouseovermouseenter

  var test = document.getElementById("test");

  test.addEventListener("mouseenter", handlerClickFunction);

答案 3 :(得分:0)

在下面的示例中,弹出窗口在鼠标悬停时打开,而不是单击,并在用户鼠标移除时隐藏它:

map_1.save('map_1.html')
import re
import fileinput

with open("map_1.html") as inf:
   txt = inf.read()

#Find all the markers names given by folium
markers = re.findall(r'\bmarker_\w+', txt)
markers = list(set(markers))

for linenum,line in enumerate( fileinput.FileInput("map_1.html",inplace=1) ):
    pattern = markers[0] + ".bindPopup"
    pattern2 = markers[0] + ".on('mouseover', function (e) {this.openPopup();});"
    pattern3 = markers[0] + ".on('mouseout', function (e) {this.closePopup();});"

    if pattern in line:
       print(line.rstrip())
       print(pattern2)
       print(pattern3)
    else:
       print(line.rstrip())