我的代码计算源和目的地之间的距离和持续时间(A - > B)。我想在相同的计算中包括反向路线(B→> A)。
我需要点击“计算”按钮来计算总距离(A-> B)+(B-> A)。
请高手帮忙谢谢。
$(document).ready(function() {
var campos_max = 8;
var x = 1;
$('#add_field').click (function(e) {
e.preventDefault(); //prevent new clicks
if (x < campos_max) {
$('#lists').append('<div class="divLista">\
<td width="80">Point 0'+ x +': </td><td width="150"><input type="text" placeholder="Point 0'+ x +'" class="points" id="waypoint'+ x +'"> <input type="button" value="-" class="remove_campo"></td></div>');
new google.maps.places.Autocomplete((document.getElementById('waypoint'+ x)),{types: ['geocode']});
x++;
}
});
// Remove div
$('#lists').on("click",".remove_campo",function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var source, destination;
var directionsDisplay;
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.Autocomplete(document.getElementById('txtSource'));
new google.maps.places.Autocomplete(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(40.659036, -73.937796);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("dvMap"), myOptions);
directionsDisplay.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
function calcRoute() {
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var elem = document.getElementsByClassName( 'points' );
var wayPoints = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].attributes.class !== "undfined") {
if(elem[i].attributes.class.value === "points"){
wayPoints.push({
location: elem[i].value,
stopover: true
});
}
}
}
var request = {
origin: source,
destination: destination,
waypoints: wayPoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
}
computeTotalDistance(response);
} else {
}
});
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
function timeConvert(time) {
seconds = time;
minutes = Math.floor(seconds/60);
hours = Math.floor(minutes/60);
days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
return (days>0?days + " dia ":"") + (hours>0?hours + " h ":"") + (minutes>0?minutes + " min":"");
}
document.getElementById("total").innerHTML = "Distance: " + totalDist.toFixed(1).replace('.',',') + " km<br>Time: " + timeConvert(totalTime);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
html, body {
margin:0;
font-family:"Segoe UI","Lucida Grande",Verdana,Arial,Helvetica,sans-serif;
font-size:14px;
height:100%;
}
.painelLateral{
float:left;
width:350px;
height:100%;
min-height:100%;
}
.dvMap{
float:right;
width:calc(100% - 350px);
height:100%;
min-height:100%;
}
.divLista{
margin-bottom: 5px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script src="http://maps.google.com/maps/api/js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<div class="painelLateral">
<form id="painel" name="painel">
<table width="350" border="0" cellspacing="5" cellpadding="0">
<tr>
<td width="102">Source:</td>
<td width="210"><input type="text" placeholder="Source" id="txtSource" style="width: 200px" /></td>
<td width="72"> </td>
</tr>
<tr>
<td colspan="2"><table width="300" border="0" cellspacing="5" cellpadding="0">
<tr></tr>
</table >
<div id="lists" align="right"></div></td>
<td><input type="button" id="add_field" value="+" /></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" placeholder="Destination" id="txtDestination" style="width: 200px" /></td>
<td> </td>
</tr>
<tr>
<td><input type="button" value="Calc" onclick="calcRoute();" /></td>
<td> </td>
<td> </td>
</tr>
</table>
<div id="dvDistance"></div>
<div id="directions_panel"></div>
<div id="total"></div>
</form>
</div>
<div class="dvMap" id="dvMap"></div>
</body>
</html>
答案 0 :(得分:0)
由于你已经得到了A-> B点,所以为什么不把那些计算距离的代码移动到它自己的函数并转换源和放大器。函数参数的目的地。
function distanceService{source,destination)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},
function (response, status) {
.......
});
return service;
}
然后你可以使用它:
distanceService(A,B); or distanceService(B,A);
通过这样做,您将能够动态构建服务,将A-&gt; B切换到B-&gt; A,访问距离变量并对生成的对象执行计算。
答案 1 :(得分:0)
将source
和destination
设置为起点/终点(A点),在目的地点设置航点(B点)。结果将是期望的结果。
var request = {
origin: source,
destination: source,
waypoints: [{location: destination, stopover: true}],
travelMode: google.maps.TravelMode.DRIVING
};
代码段
var options = {
componentRestrictions: {
country: 'br'
}
};
var source, destination;
var directionsDisplay;
var directionsService;
google.maps.event.addDomListener(window, 'load', function() {
directionsService = new google.maps.DirectionsService();
new google.maps.places.Autocomplete(document.getElementById('txtSource'), options);
new google.maps.places.Autocomplete(document.getElementById('txtDestination'), options);
directionsDisplay = new google.maps.DirectionsRenderer({
'draggable': true
});
});
var mumbai = new google.maps.LatLng(40.659036, -73.937796);
var mapOptions = {
zoom: 5,
center: mumbai
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
function GetRoute() {
directionsDisplay.setMap(map);
//directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTES**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: source,
waypoints: [{
location: destination,
stopover: true
}],
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},
function(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration + "<br />";
} else {
alert("Could not trace this route.");
}
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
body {
font-family: Arial;
font-size: 10pt;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
<br/> Destination:
<input type="text" id="txtDestination" style="width: 200px" />
<br />
<input type="button" value="Calc" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>