我无法理解这是什么问题?我在Google Map API中使用了这个示例:Simple Map
<body>
<!-- Map Section -->
<section id="map"></section>
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5Y8CqFe-4Egzl5TlPqlFvjRGcuCfHGvY&callback=initMap" async defer></script>
</body>
main.js:
//--------------------------------------------------
// Contact Map
//--------------------------------------------------
function initMap() {
if ($("#map").length > 0)
{
var map;
map = new google.maps.Map(document.getElementById('map'),{
center: {lat: 44.4297538, lng: 26.0649221},
zoom: 16,
scrollwheel: false,
zoomControl: false,
panControl: false,
streetViewControl: false,
mapTypeControl: false,
overviewMapControl: false,
clickable: false
});
}
}
错误:
消息:“initMap不是函数”
name:“InvalidValueError”
答案 0 :(得分:2)
我在使用Sage(WordPress入门主题)的wordpress模板上遇到了同样的问题。
我的js被包裹着
(function($) {
// all the functions to create map, center markers, etc.
}
然后,地图在$(document).ready
我删除了(function($) { }
,只添加了$(document).ready
的函数,然后就可以了。
另外,请务必在api google地图之前加载自定义js文件:
<script src="custom-js-google-map.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
答案 1 :(得分:2)
遇到同样的问题,我个人删除了&callback=initMap
以使其正常运行。
其他线程接缝表明initMap是你应该自己构建的函数。
答案 2 :(得分:1)
尝试移动脚本
的加载<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5Y8CqFe-4Egzl5TlPqlFvjRGcuCfHGvY&callback=initMap" async defer></script>
并确保
的正确路径 <script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
最终尝试使用相对路径
<script src="./js/jquery.min.js"></script>
<script src="./js/main.js"></script>
答案 3 :(得分:0)
提供的解决方案都没有对我有所帮助。我终于在这里遇到了脚本的动态加载:https://developers.google.com/maps/documentation/javascript/overview#Loading_the_Maps_API
由于您将其加载到单独的js文件中,因此Google Map api的功能未按正确的顺序加载。
这样做可以为我解决:
// Create the script tag, set the appropriate attributes
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
script.defer = true;
// Attach your callback function to the `window` object
window.initMap = function() {
// JS API is loaded and available
// Throw your code within this, it will wait for the google api scripts to completely load
};
// Append the 'script' element to 'head'
document.head.appendChild(script);
希望这会有所帮助,我花了一天时间寻找解决方案。