javascript - 如何解决“未捕获的 ReferenceError:未定义 google”?(谷歌地图 API)
问题描述
我很难显示一个简单的标记,实际上我在 Chrome 控制台中有“未捕获的 ReferenceError: google is not defined”并且标记没有出现。我在论坛中到处搜索,但没有任何帮助。我真的看过每一篇文章,但总是出现这个错误并且没有添加任何标记。
我为您提供我的小 HTML 代码
<!DOCTYPE html>
<html lang="lv">
<head>
<title>SparkleHeart</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<link rel='icon' href='assets/img//Intersect.svg' type='image/x-icon' />
<link rel="stylesheet" href="assets/css/normalize.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<script
src="https://use.fontawesome.com/releases/v5.15.2/js/all.js"
data-auto-a11y="true"></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script src='assets/js/theme.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha512-Rc24PGD2NTEGNYG/EMB+jcFpAltU9svgPcG/73l1/5M6is6gu3Vo1uVqyaNWf/sXfKyI0l240iwX9wpm6HE/Tg==" crossorigin="anonymous"></script>
</head>
<body>
<main>
<div>
<!-- Drop-Down Filter Menu -->
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Please select category</option>
<option value="Branch">Branch</option>
<option value="ATM">ATM</option>
<option value="Drive-Thru">Drive-Thru</option>
<!--Add more "options" for the dropdown menu-->
</select>
<div id="map-canvas"></div>
</div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBGwz_8OxIGhS_nOIPS2F_mH1ie5WfmhZ0&map_ids=e24b393c59b842b4&callback=initMap" async defer>
</script>
</main>
</body>
</html>
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
// Function to init map
function initMap() {
var center = new google.maps.LatLng(56.9496,24.1052);
var mapOptions = {
zoom: 14,
center: center,
mapId: 'e24b393c59b842b4',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
// Function to add markers to map
function addMarker(marker) {
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener (zoom in and open info window)
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(13);
}
})(marker1, content));
}
// Function to filter markers by category
filterMarkers = function (category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// if Categories don't match
else {
marker.setVisible(false);
}
}
}
// Add markers (you can add as many as you like)
// Note, marker #5 has a lot of styling and an image in the info window. Just showing an example of what you can do with an info window.
markers1 = [
['0', 'Lee Blvd Branch', 56.9496, 24.1052, 'Branch'],
['1', 'Lee Blvd ATM', 34.613839, -98.409974, 'ATM'],
['2', 'Annex Branch', 34.607799, -98.396419, 'Branch'],
['3', 'West Branch', 34.623425, -98.468883, 'Drive-Thru'],
['4', 'East ATM', 34.593839, -98.409974, 'ATM'],
['5', '<div style=\"font-size:12px; color:#000; \"><img id=\'popimg\' src=\'https://s3-us-west-2.amazonaws.com/s.cdpn.io/44720/paris.jpg\' <br/><br/><strong>Address:</strong><br/>123 Happy Place<br/><br/><strong>City-State-Zip:</strong><br/>Lawton, OK. 73509<br/><br/><strong>Phone:</strong><br/>580-555-1234<br/><br/> <strong>Type:</strong><br/>(ATM)<br/><br/><strong>Monday - Friday</strong><br/>9:00 AM - 5:00 PM                    </div>"', 34.713839, -98.409974, 'ATM']
];
// Init map
initMap();
解决方案
The error google is not defined
was thrown because you tried to use the google
object before it is defined:
var infowindow = new google.maps.InfoWindow({
content: ''
});
And it is defined by the script call to https://maps.googleapis.com/maps/api/js
which is loaded asynchonously. So as soon as it is loaded, the initMap()
function runs because it was passed to the request: &callback=initMap
So you do not have to call initMap
in your code.
I added two console.logs to show the initMap
is running and that 5 markers are added. There is a weird Script error.
message shown in the snippet below and I can't understand why... But it does not show in CodePen
#map-canvas{
height: 500px;
}
<html lang="lv">
<head>
<title>SparkleHeart</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<!--link rel='icon' href='assets/img//Intersect.svg' type='image/x-icon' />
<link rel="stylesheet" href="assets/css/normalize.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<script--
src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-a11y="true"></script-->
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<!--script src='assets/js/theme.js'></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha512-Rc24PGD2NTEGNYG/EMB+jcFpAltU9svgPcG/73l1/5M6is6gu3Vo1uVqyaNWf/sXfKyI0l240iwX9wpm6HE/Tg==" crossorigin="anonymous"></script>
</head>
<body>
<main>
<div>
<!-- Drop-Down Filter Menu -->
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Please select category</option>
<option value="Branch">Branch</option>
<option value="ATM">ATM</option>
<option value="Drive-Thru">Drive-Thru</option>
<!--Add more "options" for the dropdown menu-->
</select>
<div id="map-canvas"></div>
</div>
<script>
var gmarkers1 = [];
var markers1 = [];
//var infowindow; // = new google.maps.InfoWindow({
// content: ''
//});
// Function to init map
function initMap() {
console.log("init map")
infowindow = new google.maps.InfoWindow({content: ''});
var center = new google.maps.LatLng(56.9496, 24.1052);
var mapOptions = {
zoom: 14,
center: center,
mapId: "e24b393c59b842b4"
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
// Function to add markers to map
function addMarker(marker) {
console.log("Add marker",marker)
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener (zoom in and open info window)
google.maps.event.addListener(
marker1,
"click",
(function(marker1, content) {
return function() {
console.log("Gmarker 1 gets pushed");
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(13);
};
})(marker1, content)
);
}
// Function to filter markers by category
//filterMarkers = function (category) {
function filterMarkers(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// if Categories don't match
else {
marker.setVisible(false);
}
}
}
// Add markers (you can add as many as you like)
// Note, marker #5 has a lot of styling and an image in the info window. Just showing an example of what you can do with an info window.
markers1 = [
["0", "Lee Blvd Branch", 56.9496, 24.1052, "Branch"],
["1", "Lee Blvd ATM", 34.613839, -98.409974, "ATM"],
["2", "Annex Branch", 34.607799, -98.396419, "Branch"],
["3", "West Branch", 34.623425, -98.468883, "Drive-Thru"],
["4", "East ATM", 34.593839, -98.409974, "ATM"],
[
"5",
"<div style=\"font-size:12px; color:#000; \"><img id='popimg' src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/44720/paris.jpg' <br/><br/><strong>Address:</strong><br/>123 Happy Place<br/><br/><strong>City-State-Zip:</strong><br/>Lawton, OK. 73509<br/><br/><strong>Phone:</strong><br/>580-555-1234<br/><br/> <strong>Type:</strong><br/>(ATM)<br/><br/><strong>Monday - Friday</strong><br/>9:00 AM - 5:00 PM                    </div>\"",
34.713839,
-98.409974,
"ATM"
]
];
// Init map
//initMap();
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBGwz_8OxIGhS_nOIPS2F_mH1ie5WfmhZ0&map_ids=e24b393c59b842b4&callback=initMap" async defer>
</script>
</main>
</body>
</html>
推荐阅读
- c# - 具有多个字段的 Word 互操作页眉和页脚
- python-3.x - python3.6帮助命令转储核心,当我们尝试帮助(tensorflow)
- sql - SQL Server Alwayson 和复制合并
- javascript - for 循环内的 JS DOM 不能使用字符串
- aws-elasticsearch - AWS Elasticsearch 服务获取 NodeId(实例 ID)
- javascript - AWS Amplify 和 amazon-cognito-identity-js 的区别?
- javascript - Java Script 无法从动态创建的表中检索数据
- conditional-statements - 解决autoit中的多条件问题
- c# - 读取在数据表 c# 中动态创建的复选框值
- python - 在 Python 中重命名命名参数以避免与 import 语句的命名冲突