我试图编译谷歌的示例代码并找出总距离,我相信脚本不是错误的......如果是的话。谷歌地图不会显示...有些东西丢失..任何人都可以帮助..
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP].push(control);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
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);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById("total").innerHTML = total + " km";
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="control">
<strong>Start:</strong>
<select id="start" onchange="calcRoute();">
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select>
<strong>End:</strong>
<select id="end" onchange="calcRoute();">
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select>
</div>
<div id="total"></div>
<div id="directions-panel"></div>
<div id="map_canvas"></div>
</body>
答案 0 :(得分:1)
尝试
computeTotalDistance(response)
而不是
computeTotalDistance(result)`
答案 1 :(得分:1)
您永远不会调用您的computeTotalDistance函数。您需要在DirectionsService.route回调函数中调用它。
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotalDistance(response);
}