Google Maps API地图加载后闪显消失问题求助
Google地图闪显后消失的问题排查与解决
复制Google官方文档中的代码并填入API密钥后,页面加载时地图仅闪显一秒就消失,已尝试Stack Overflow搜索解决方案但未解决。
相关代码
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "REDACTED", v: "weekly", }); async function initMap() { const { Map } = await google.maps.importLibrary('maps') map = new Map(document.querySelector('#main > div:first-child > section:nth-child(1)'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }) // google.maps.event.trigger(map, 'resize'); } initMap()
相关截图


排查与解决步骤
1. 给地图容器设置固定宽高
Google地图需要挂载的DOM元素必须有明确的宽高,否则初始化后可能因布局重排导致消失。给目标section添加CSS样式:
#main > div:first-child > section:nth-child(1) { width: 100%; height: 400px; min-height: 400px; }
或者直接在容器元素上添加行内样式:<section style="width:100%;height:400px;">
2. 验证容器选择器的有效性
初始化地图前先确认选中的容器存在,避免因DOM未加载完成导致元素为null:
async function initMap() { const container = document.querySelector('#main > div:first-child > section:nth-child(1)'); console.log(container); // 控制台检查是否输出DOM元素,而非null if (!container) return; const { Map } = await google.maps.importLibrary('maps'); map = new Map(container, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }
3. 避免全局变量被覆盖
将map声明为局部变量,防止被其他代码意外覆盖:
async function initMap() { const container = document.querySelector('#main > div:first-child > section:nth-child(1)'); if (!container) return; const { Map } = await google.maps.importLibrary('maps'); const map = new Map(container, { // 声明为局部变量 center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); // 若需全局访问,可挂载到window:window.map = map; }
4. 检查API密钥与控制台错误
打开浏览器开发者工具控制台(F12),查看是否有Google Maps相关错误:
- API密钥未启用Maps JavaScript API
- 密钥配额耗尽
- 域名未加入密钥的允许列表
内容的提问来源于stack exchange,提问作者oldboy
相关产品推荐
相关产品推荐

