我正在尝试在我的网站上设置谷歌地图API,以便我提供的部分送货服务。我直接从developers.google.com上的示例中复制了代码,但由于某些原因我的地图不会加载到我的页面上!我已多次浏览代码并且无法加载...帮助!
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBPiGhEEN1WjNHOtVoOMufbwsj_thBse2w&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.mapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
html:
<body onload="initialize()">
<div class="map-canvas" style= "height: 100%">
</div>
</body>
答案 0 :(得分:1)
我收到了一个javascript错误:Uncaught TypeError: Cannot read property 'ROADMAP' of undefined
此:
mapTypeId: google.maps.mapTypeId.ROADMAP,
应该是:
mapTypeId: google.maps.MapTypeId.ROADMAP,
主要问题是:Uncaught TypeError: Cannot read property 'offsetWidth' of null
因为您的网页没有id =“map-canvas”的div:
<div class="map-canvas" style= "height: 100%">
应该是:
<div id="map-canvas" style= "height: 100%;">
您也在调用两次初始化,更改:
<body onload="initialize()">
致:
<body>
完整页面(在本地工作):
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body >
<div id="map-canvas" style= "height: 100%;">
</div>
</body>
</html>
答案 1 :(得分:0)
我看到三个问题
此外,由于您使用的是addDomListener,因此也不必在body标签上也有onload事件。我只想使用addDomListener。
<!DOCTYPE html>
<head>
<title>Google Maps</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBPiGhEEN1WjNHOtVoOMufbwsj_thBse2w&sensor=true">
</script>
<style>
#map-canvas{
height: 400px;
}
</style>
</head>
<body>
<div id="map-canvas">
</div>
</body>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</html>