我有这个代码:
<html>
<head>
<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 copenhagen = new google.maps.LatLng(55.6771, 12.5704);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: copenhagen
}
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 distanceInput = document.getElementById("distance");
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);
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
}
});
}
</script>
<title>Distance Calculator</title>
<style type="text/css">
body {
font-family:Helvetica, Arial;
}
#map_canvas {
height: 50%;
}
</style>
</head>
<body>
<body onload="initialize()">
<p>Enter your current location and desired destination to get the distance</p>
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" />
<br>
<label for="end">End: </label>
<input type="text" name="end" id="end" />
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<script>
var cost=distance*2-(distance*2*0.20)
document.write("Cost: ");
document.write(cost + "<br>");
</script>
</p>
</div>
<div id="map_canvas"></div>
</body>
</html>
问题中的代码是这样的:
<script>
var cost=distance*2-(distance*2*0.20)
document.write("Cost: ");
document.write(cost + "<br>");
</script>
此代码要求用户提供起始地址和目标地址,并使用 Google Maps API 计算两点之间的距离。然后,我添加了功能,使用他们的区域统一费率公式(距离以公里为单位)*2-20% 计算出租车行驶该距离所需的费用。
我的问题在于“距离”变量是在 API 代码中定义的,所以当我在计算成本时引用它时,它似乎并没有延续......就像它甚至不存在一样。我知道这与它在与尝试使用它的下标不同的下标中定义有关。任何和所有的建议表示赞赏!