我正在尝试学习Google Maps API以获取从Point-A到Point-B的路线。当我只是尝试tutorial中的示例代码时,我的Javascript控制台将我带到了一些我无法理解的代码部分,调试器停在一行“请参阅服务条款以获取更多信息:{{ 3}}。“以下是我的HTML代码列表:
<html>
<head>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false">
</script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsDisplay.setMap(map);
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function calcRoute() {
initialize()
var start = "Sydney, NSW";
var end = "Chatswood, NSW";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onload="calcRoute()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
地图会显示在浏览器中,但路线不会显示。谁能在这里看到问题?任何帮助将不胜感激。
答案 0 :(得分:4)
问题在于这两行的顺序:
directionsDisplay.setMap(map);
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
反转它们并且它应该工作,将Directions Renderer的地图设置为null(或未定义),从地图中删除方向。我将它们更改为(因此将地图分配给全局地图变量):
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
directionsDisplay.setMap(map);
代码段
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
initialize()
var start = "Sydney, NSW";
var end = "Chatswood, NSW";
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
@media print {
html,
body {
height: auto;
}
#map_canvas {
height: 650px;
}
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="calcRoute()">
<div id="map_canvas" style="width:100%; height:100%"></div>