Gmaps无法显示地图:jupyter-gmaps已加载但无法实例化
问题描述
运行以下gmaps入门代码时,数据集表格可正常显示,但地图无法加载,出现两个关键错误:
- 来自模块'jupyter-gmaps'的'FigureModel'类已加载但无法实例化
- 浏览器控制台错误:
Refused to execute http://localhost:8888/nbextensions/gmaps.js?v=20230810111648 as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type
使用的代码:
import os import requests import gmaps import gmaps.datasets gmaps.configure(api_key="API KEY HERE") earthquake_df = gmaps.datasets.load_dataset_as_df('earthquakes') earthquake_df.head() locations = earthquake_df[['latitude', 'longitude']] weights = earthquake_df['magnitude'] fig = gmaps.figure() fig.add_layer(gmaps.heatmap_layer(locations, weights=weights)) fig
解决方案
1. 重装并修复gmaps扩展
错误核心是Jupyter服务器返回的gmaps.js文件MIME类型不正确,先通过重装解决:
- 卸载现有包:
pip uninstall -y gmaps jupyter-gmaps - 清理旧的nbextension缓存:
jupyter nbextension uninstall --py gmaps - 安装稳定版本的gmaps(推荐0.9.0):
pip install gmaps==0.9.0 - 重新启用扩展:
jupyter nbextension enable --py gmaps - 重启Jupyter服务器后重新运行代码。
2. 调整Jupyter的内容类型头设置
如果重装无效,临时关闭X-Content-Type-Options: nosniff头:
- 生成Jupyter配置文件(未生成过的话执行):
jupyter notebook --generate-config - 打开配置文件(路径通常是
~/.jupyter/jupyter_notebook_config.py),添加以下配置:c.NotebookApp.tornado_settings = {'headers': {'X-Content-Type-Options': ''}} - 保存后重启Jupyter服务器。
3. 切换到JupyterLab
Jupyter Notebook的扩展兼容性问题较多,换用JupyterLab试试:
- 安装JupyterLab:
pip install jupyterlab - 安装gmaps的JupyterLab扩展:
jupyter labextension install @jupyter-widgets/jupyterlab-manager gmaps - 启动JupyterLab,重新运行代码。
4. 检查Google API密钥权限
确保你的API密钥已经启用了Maps JavaScript API和Geocoding API,本地测试时暂时关闭IP限制(避免密钥被拦截)。
内容的提问来源于stack exchange,提问作者mnine
相关产品推荐
相关产品推荐

