【问题标题】:Show path in folium map by clicking or hovering marker通过单击或悬停标记在 folium 地图中显示路径
【发布时间】:2022-12-17 17:29:03
【问题描述】:

我制作了一个带有很多标记的 folium 地图,每个标记都有一个工具提示和一个充满 html 格式文本的弹出窗口。对于标记定义的每个位置,我都有额外的地理数据点,我想将其显示为线/路径/路线/ AntPath .. 无论如何。 我的问题:仅当您单击标记(--> 也打开弹出窗口)或悬停标记(--> 打开工具提示)时,附加行才会出现。

我不知道这是否可能,希望能在这里找到一些灵感

这是一个可以在 jupyter 中使用的示例。安装 pandas 和 folium 后,它应该可以工作。我添加了一些 AntPath,但它们从未像在地图中那样消失。如果你将它们添加到 markercluster,蚂蚁就不会移动,如果我将它们添加到弹出窗口,一切都会被破坏。


# imports
import pandas as pd
import folium
from folium.plugins import HeatMap, AntPath

# functions
def segmrk(latlng, geopath, pop='some text in the popup', tool='tooltiptext<br>in html'):
    # define marker
    style = ['bicycle', 'blue', '#FFFFFF']
    # popup
    iframe = folium.IFrame(pop,  # html style text .. next step: change font!!
                           width=200,
                           height=200
                           )
    fpop = folium.Popup(iframe)
    #AntPath(geopath).add_to(fpop)
    
    # marker
    mrk = folium.Marker(location=latlng,
                        popup=fpop,
                        tooltip=tool,
                        icon=folium.Icon(icon=style[0], prefix='fa',
                                         color=style[1],
                                         icon_color=style[2]
                                         ),
                        )
    return mrk

# sample data
df = pd.DataFrame()
df['geo'] = [[52.5172, 12.1024],[52.5172, 12.2024],[52.5172, 12.3024]]
df['geo_path'] = [[[52.5172, 12.1024],[52.6172, 12.1024],[52.7172, 12.1024],[52.7172, 12.1024]],
                  [[52.5172, 12.2024],[52.6172, 12.2024],[52.7172, 12.2024],[52.7172, 12.2024]],
                  [[52.5172, 12.3024],[52.6172, 12.3024],[52.7172, 12.3024],[52.7172, 12.3024]],
                 ]

# define map

geo_start = [52.5172, 12.2024]
dmap = folium.Map(location=geo_start,
                  zoom_start=10,
                  tiles='OpenStreetMap'
                  )

mapstyle_2 = folium.raster_layers.TileLayer(tiles='CartoDB dark_matter',
                                            name='dark',
                                            overlay=False,
                                            control=True,
                                            show=True,
                                            )
mapstyle_2.add_to(dmap)

# add full screen button
folium.plugins.Fullscreen().add_to(dmap)


# add layercontrol

# markergroups in layercontrol
mc = folium.plugins.MarkerCluster(name='Segment Markers',
                                  overlay=True,
                                  control=True,
                                  show=True,
                                  disableClusteringAtZoom=10
                                  )
mc.add_to(dmap)
mcsub1 = folium.plugins.FeatureGroupSubGroup(mc, name='- markers subcluster',
                                             show=True,
                                             control=False)  # checkmark actually not shown
mcsub1.add_to(dmap)

# the layercontrol itself
lc = folium.map.LayerControl(collapsed=False)
lc.add_to(dmap)

# add geo markers
for _, data in df.iterrows():
    mrk = segmrk(data['geo'], data['geo_path'])
    mrk.add_to(mcsub1)
    # this AntPath should be shown when popup appears OR when hovering marker
    AntPath(data['geo_path']).add_to(dmap)
    
# show map
dmap

【问题讨论】:

    标签: python folium


    【解决方案1】:

    如果你没有太多的标记,你可以试试这个。

    # imports
    import pandas as pd
    import folium
    from folium.plugins import HeatMap
    from folium.map import Marker, Template
    
    # sample data
    df = pd.DataFrame()
    df['geo'] = [[52.5172, 12.1024],[52.5172, 12.2024],[52.5172, 12.3024]]
    df['geo_path'] = [[[52.5172, 12.1024],[52.6172, 12.1024],[52.7172, 12.1024],[52.7172, 12.1024]],
                      [[52.5172, 12.2024],[52.6172, 12.2024],[52.7172, 12.2024],[52.7172, 12.2024]],
                      [[52.5172, 12.3024],[52.6172, 12.3024],[52.7172, 12.3024],[52.7172, 12.3024]],
                     ]
    
    # define map
    
    geo_start = [52.5172, 12.2024]
    dmap = folium.Map(location=geo_start,
                      zoom_start=10,
                      tiles='OpenStreetMap'
                      )
    
    mapstyle_2 = folium.raster_layers.TileLayer(tiles='CartoDB dark_matter',
                                                name='dark',
                                                overlay=False,
                                                control=True,
                                                show=True,
                                                )
    mapstyle_2.add_to(dmap)
    
    # add full screen button
    folium.plugins.Fullscreen().add_to(dmap)
    
    # Modify Marker template to include the onClick event
    click_template = """{% macro script(this, kwargs) %}
        var {{ this.get_name() }} = L.marker(
            {{ this.location|tojson }},
            {{ this.options|tojson }}
        ).addTo({{ this._parent.get_name() }}).on('click', onClick);
    {% endmacro %}"""
    
    # Change template to custom template
    Marker._template = Template(click_template)
    
    
    
    # add layercontrol
    
    # markergroups in layercontrol
    mc = folium.plugins.MarkerCluster(name='Segment Markers',
                                      overlay=True,
                                      control=True,
                                      show=True,
                                      disableClusteringAtZoom=10
                                      )
    mc.add_to(dmap)
    mcsub1 = folium.plugins.FeatureGroupSubGroup(mc, name='- markers subcluster',
                                                 show=True,
                                                 control=False)  # checkmark actually not shown
    mcsub1.add_to(dmap)
    
    
    # the layercontrol itself
    lc = folium.map.LayerControl(collapsed=False)
    lc.add_to(dmap)
    
    # Create the onClick listener function as a branca element and add to the map html
    map_id = dmap.get_name()
    click_js = f"""function onClick(e) {{                
                        
                                     
                     var coords = e.target.options.pathCoords;
                     //var coords = JSON.stringify(coords);
                     //alert(coords);
                     var ant_path = L.polyline.antPath(coords, {{
                    "delay": 400,
                    "dashArray": [
                        10,
                        20
                    ],
                    "weight": 5,
                    "color": "#0000FF",
                    "pulseColor": "#FFFFFF",
                    "paused": false,
                    "reverse": false,
                    "hardwareAccelerated": true
                    }}); 
                    
                    {map_id}.eachLayer(function(layer){{
                       if (layer instanceof L.Polyline)
                          {{ {map_id}.removeLayer(layer) }}
                          }});
                         
                    ant_path.addTo({map_id});
                     }}"""
                     
    e = folium.Element(click_js)
    html = dmap.get_root()
    html.script.add_child(e)
    
    
    # add geo markers
    for index, data in df.iterrows():
        mrk = folium.Marker(data['geo'], pathCoords=data['geo_path'])
        mrk.add_to(mcsub1)
        
    # Add leaflet antpath plugin cdn link
    link = folium.JavascriptLink("https://cdn.jsdelivr.net/npm/leaflet-ant-path@1.3.0/dist/leaflet-ant-path.js")
    dmap.get_root().html.add_child(link)  
    # show map
    
    dmap
    ​
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2017-12-29
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 2022-09-28
      相关资源
      最近更新 更多