使用 Folium 和 Pandas 的多个位置的自定义图标

问题描述 投票:0回答:1

我正在尝试遍历 pandas 数据框,使用自定义图标而不是默认图标作为标记在 Folium 地图上绘制多个地理位置。

首先我创建一个熊猫数据框如下:

# dependencies
import folium 
import pandas as pd 

from google.colab import drive
drive.mount('/content/drive/')

    # create dummy data
    df = {'Lat': [22.50, 63.21, -13.21, 33.46],
                'Lon': [43.91, -22.22, 77.11, 22.11],
                'Color': ['red', 'yellow', 'orange', 'blue']
              }
      
# create dataframe
data = pd.DataFrame(df)

然后我创建一个缩放系数为 2 的世界地图:

world = folium.Map(
    zoom_start=2
    )

我可以通过遍历数据框行来绘制位置,如下所示:

x = data[['Lat', 'Lon', 'Color']].copy()

    for index, row in x.iterrows():
        folium.Marker([row['Lat'], row['Lon']],
                            popup=row['Color'],
                            icon=folium.Icon(color="red", icon="info-sign")
                           ).add_to(world)
    
    world

这会产生以下图形:

为了使用自定义图标,我需要使用

folium.features.CustomIcon
并将图像路径声明为我的 Google Drive 上存储图像的位置。

pushpin = folium.features.CustomIcon('/content/drive/My Drive/Colab Notebooks/pushpin.png', icon_size=(30,30))

我可以在地图上的一个指定位置使用它,如下所示:

world = folium.Map(
    zoom_start=2
    )

folium.Marker([40.743720, -73.822030], icon=pushpin).add_to(world)
world 

产生以下图形

但是,当我尝试在迭代中使用自定义图标时,它似乎不起作用,并且只绘制带有默认标记的第一个坐标对。

pushpin = folium.features.CustomIcon('/content/drive/My Drive/Colab Notebooks/pushpin.png', icon_size=(30,30))
    
    world = folium.Map(
    zoom_start=2
    )
            
    x = data[['Lat', 'Lon', 'Color']].copy()
            
    for index, row in x.iterrows():
         folium.Marker([row['Lat'], row['Lon']],
                                    icon=pushpin,
                                    popup=row['Color'],
                                   ).add_to(world)
            
            
            world

如图:

我的期望是用图钉标记绘制所有 4 个位置。

非常感谢任何帮助。

python pandas leaflet geolocation folium
1个回答
1
投票

似乎唯一的方法是将自定义图标调用放在 for 循环中,以便为每次迭代初始化,例如:

    world = folium.Map(
    zoom_start=2
    )
            
    x = data[['Lat', 'Lon', 'Color']].copy()
            
    for index, row in x.iterrows():
         pushpin = folium.features.CustomIcon('/content/drive/My Drive/Colab Notebooks/pushpin.png', icon_size=(30,30))
         folium.Marker([row['Lat'], row['Lon']],
                                    icon=pushpin,
                                    popup=row['Color'],
                                   ).add_to(world)
            
            
    world

这会产生以下图形:

© www.soinside.com 2019 - 2024. All rights reserved.