Python gmaps库marker_layer无法使用问题求助
gmaps marker_layer在Python 3.10中报错AttributeError: module 'collections' has no attribute 'Iterable'
在MacOS系统上使用VSCode的Jupyter Notebook扩展(Python 3.10.11版本)时,gmaps的heatmap_layer可以正常运行,但marker_layer调用时报错,错误信息如下:
AttributeError Traceback (most recent call last) Cell In[3], line 17 15 fig = gmaps.figure() 16 # create the markers layer ---> 17 markers = gmaps.marker_layer(locations) 18 # add the markers layer to the map 19 fig.add_layer(markers) File ~/anaconda3/lib/python3.10/site-packages/gmaps/marker.py:553, in marker_layer(locations, hover_text, label, info_box_content, display_info_box) 485 @doc_subst(_doc_snippets) 486 def marker_layer( 487 locations, hover_text='', label='', 488 info_box_content=None, display_info_box=None): 489 """ 490 Marker layer 491 (...) 551 A :class:`gmaps.Markers` instance. 552 """ ---> 553 marker_options = _marker_layer_options( 554 locations, hover_text, label, info_box_content, display_info_box) 555 markers = [Marker(**option) for option in marker_options] 556 return Markers(markers=markers) ... 39 isinstance(elem, string_types) or ---> 40 not isinstance(elem, collections.Iterable) 41 ) AttributeError: module 'collections' has no attribute 'Iterable'
使用的代码如下:
# 导入gmaps包并配置API密钥 import gmaps gmaps.configure(api_key="****") # 要标记的经纬度列表 locations = [ (-34.0, -59.166672), (-32.23333, -64.433327), (40.166672, 44.133331), (51.216671, 5.0833302), (51.333328, 4.25) ] # 创建初始地图 fig = gmaps.figure() # 创建标记图层 markers = gmaps.marker_layer(locations) # 将标记图层添加到地图 fig.add_layer(markers) # 显示最终地图 fig
解决方法
这个错误的根源是Python 3.10及以上版本中,collections.Iterable被移到了collections.abc模块下,而旧版本的gmaps库仍在使用过时的引用方式。可以通过以下几种方式解决:
临时补丁法:在导入gmaps之前,添加兼容性代码,手动将
collections.Iterable指向新的位置:import collections import collections.abc collections.Iterable = collections.abc.Iterable # 之后再导入gmaps import gmaps gmaps.configure(api_key="****")升级gmaps到开发版本:官方可能已经修复了这个兼容性问题,安装最新的开发版:
pip install git+https://github.com/pbugnion/gmaps.git手动修改库文件:找到gmaps库中报错的文件(比如报错信息里的
gmaps/marker.py以及其他引用collections.Iterable的文件),将所有collections.Iterable替换为collections.abc.Iterable,并确保文件顶部有from collections.abc import Iterable或者使用完整路径引用。
内容的提问来源于stack exchange,提问作者Will McCall
相关产品推荐
相关产品推荐

