请参阅下面的代码。我收到以下错误:
错误:未定义响应,这发生在
中distanceInput.value = response.routes[0].legs[0].distance.value;
(它应该有效,但不是)
我现在搜索了很长时间,有人可以帮帮我吗? 提前谢谢
距离计算器
<style type="text/css">
#map_canvas
{ height: 100px;
}
</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?&sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(-37.813187, 144.96298);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
var directionsService = new google.maps.DirectionsService();
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);
}
});
var distanceInput = document.getElementById("distance");
distanceInput.value = response.routes[0].legs[0].distance.value;
}
</script>
</head>
<body onload="initialize()">
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" />
<label for="end">End: </label>
<input type="text" name="end" id="end" />
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Distance (km): </label>
<input type="text" name="distance" id="distance"/>
</p>
</div>
<div id="map_canvas"></div>
</body>
答案 0 :(得分:0)
response
将不存在,因此请尝试在directionsService.route
的回调中设置它,如:
...
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var distanceInput = document.getElementById("distance");
distanceInput.value = response.routes[0].legs[0].distance.value;
}
});
...
答案 1 :(得分:0)
因为 response
超出了范围。因此,您必须在 directionsService.route
方法内移动。
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var distanceInput = document.getElementById("distance");
distanceInput.value = response.routes[0].legs[0].distance.value;
}
});