已配置API Key仍提示Google is not defined,地图标记遍历问题求助
解决“Google is not defined”错误及Google Maps标记加载问题
我看了你的代码,问题主要出在Google Maps脚本的加载参数错误和函数执行时机不对上,咱们一步步来修复:
问题分析
- API脚本URL格式错误:你当前的脚本URL里,
key=THEAPIKEY=initMap是错误的写法,回调函数参数应该用&callback=initMap来连接,不是第二个等号,这会导致Google Maps SDK无法正确加载并触发初始化逻辑。 loop()执行过早:你直接在全局作用域调用loop(),这时候Google Maps的脚本还没加载完成,google对象压根还不存在;而且initMap()还没执行,map变量也没有被初始化,自然会报错。- 额外注意:要确保
localStorage.getItem("lat2")返回的是合法的JSON数组,格式应该是类似[[39.9042, 116.4074], [31.2304, 121.4737]]这样的坐标数组集合。
修复步骤
1. 修正Google Maps脚本URL
把脚本的src属性改成正确格式,记得替换成你实际的API密钥:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=你的实际API密钥&callback=initMap"></script>
这里用&来连接key和callback参数,是URL参数的标准写法。
2. 调整loop()的执行时机
把loop()的调用放到initMap()函数内部,确保Google Maps已经初始化完成、map变量也已赋值后再执行标记创建逻辑:
function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 2, center: new google.maps.LatLng(2.8,-187.3), mapTypeId: 'terrain' }); // 地图初始化完成后再调用loop创建标记 loop(); }
同时删掉全局作用域里的loop()调用,避免过早执行。
3. (可选)增加错误处理
为了避免localStorage数据不存在或格式错误导致的崩溃,可以在loop()里加简单的判断:
function loop() { var lati = JSON.parse(localStorage.getItem("lat2")); // 检查数据是否存在且是数组 if (!lati || !Array.isArray(lati)) { console.log("没有找到合法的坐标数据"); return; } console.log("Hi"); console.log(lati); for (var i = 0; i < lati.length; i++) { var coords = lati[i]; // 确保每个坐标是包含两个数值的数组 if (Array.isArray(coords) && coords.length === 2) { var latLng = {lat: coords[0], lng: coords[1]}; var marker = new google.maps.Marker({ position: latLng, map: map }); } } }
完整修正后的代码
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> /* Always set the map height explicitly to define the size of the div element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 2, center: new google.maps.LatLng(2.8,-187.3), mapTypeId: 'terrain' }); // 地图初始化完成后调用loop创建标记 loop(); } // Loop through the results array and place a marker for each set of coordinates. function loop() { var lati = JSON.parse(localStorage.getItem("lat2")); // 增加数据合法性判断 if (!lati || !Array.isArray(lati)) { console.log("未找到合法的坐标数据"); return; } console.log("Hi"); console.log(lati); for (var i = 0; i < lati.length; i++) { var coords = lati[i]; if (Array.isArray(coords) && coords.length === 2) { var latLng = {lat: coords[0], lng: coords[1]}; var marker = new google.maps.Marker({ position: latLng, map: map }); } } } </script> <!-- 修正后的API脚本URL --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=你的实际API密钥&callback=initMap"></script> </body> </html>
按照上面的步骤修改后,应该就能解决“Google is not defined”的错误,同时正确加载地图标记了。
内容的提问来源于stack exchange,提问作者gaBe ng
相关产品推荐
相关产品推荐

