Python使用Folium将批量JPG图片添加到地图标记弹窗的问题求助
问题排查与修复
错误原因
- 直接触发
FileNotFoundError的问题:你在对图片做base64编码的步骤open(sortedList[c], 'rb')中,只传了纯文件名,没有拼接gps/目录前缀。你的图片都存放在gps文件夹下,程序默认在当前运行的工作目录查找文件,自然找不到对应图片。你之前读取EXIF时拼接路径的写法'gps/'+sortedList[c]是正确的,此处漏写了路径前缀。 - 其余潜在问题:
os.scandir返回的是一次性迭代器,你外层写了for entry in entries:循环,内层又用列表推导式二次遍历entries,迭代器首次遍历后就为空,外层循环实际只执行一次,逻辑存在冗余隐患。- 代码中使用了
IFrame组件但没有导入,修复路径问题后还会触发NameError。 - 当前逻辑仅给第一个点位绑定了图片弹窗,其余点位只显示计数,不符合批量绑定图片的需求。
修复后代码
import os, exif, folium, base64 # 新增导入IFrame from folium import IFrame def convert_lat(coordinates, ref): latCoords = coordinates[0] + coordinates[1] / 60 + coordinates[2] / 3600 if ref == 'W' or ref == 'S': latCoords = -latCoords return latCoords coordList=[] img_list = [] # 存储有效图片路径,方便后续绑定弹窗 map = folium.Map(location=[51.50197125069916, -0.14000860301423912], zoom_start = 16) from exif import Image # 修复scandir逻辑,去掉冗余的外层for循环 with os.scandir('gps/') as entries: filename= [i.name for i in entries if not i.name.startswith('.')] sortedList = sorted(filename, key=lambda x: int(x.split("_")[1].split(".")[0])) for c in range(len(sortedList)): img_path = ('gps/'+sortedList[c]) with open (img_path, 'rb') as src: img = Image(src) if img.has_exif: latCoords = (convert_lat(img.gps_latitude, img.gps_latitude_ref)) longCoords = (convert_lat(img.gps_longitude, img.gps_longitude_ref)) coord = [latCoords, longCoords] coordList.append(coord) img_list.append(img_path) # 记录有EXIF信息的图片路径 else: print (src.name,'has no EXIF information') # 所有点位统一绑定图片弹窗 for c in range(len(coordList)): # 拼接路径读取图片做base64编码,加decode避免字节格式问题 encoded = base64.b64encode(open(img_list[c], 'rb').read()).decode('utf-8') html= '<img src="data:image/jpg;base64,{}">'.format resolution, width, height = 75, 50, 25 iframe = IFrame(html(encoded), width=(width*resolution)+20, height=(height*resolution)+20) popup = folium.Popup(iframe, max_width=1000) # 保留原有的标记样式区分首尾点 if c == 0: icon = folium.Icon(icon='home',prefix='glyphicon') elif c == (len(coordList)-1): icon = folium.Icon(icon='flag',prefix='glyphicon') else: icon = folium.Icon(icon='asterisk',prefix='glyphicon') folium.Marker(coordList[c],popup=popup,icon=icon).add_to(map) folium.PolyLine(coordList, color ="red", weight=2.5, opacity=1).add_to(map) # 导出为html文件即可打开查看效果 map.save("photo_map.html")
额外说明
如果不需要所有点位都显示图片,仅需要指定点位显示,只需要把图片弹窗的逻辑放回对应的判断分支即可,注意保持路径拼接的写法即可。
内容的提问来源于stack exchange,提问作者TLC
相关产品推荐
相关产品推荐

