我已经获得了使用Google地图进行路线计算的代码段。
<div id="map"></div>
<div id="right-panel">
<div>
<b>Standort:</b>
<select id="start">
<option value="Frankfurt">Frankfurt</option>
<option value="Duisburg">Duisburg</option>
</select>
<br>
<b>Punkt 1:</b> <br>
<input id="wayp1">
<br>
<b>Punkt 2:</b>
<input id="wayp2">
<br>
<select id="end">
<option value="Frankfurt">Frankfurt</option>
<option value="Duisburg">Duisburg</option>
</select>
<input type="submit" id="submit">
</div>
<div id="directions-panel"></div>
</div>
</div><!-- #primary -->
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 50.81, lng: 6.83}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
</script>
通过选择字段添加航点。现在我想将其更改为输入字段。
所以我创建了2个输入字段(wayp1 & wayp2)
并将waypts
部分替换为:
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var LadeValue = document.getElementById('wayp1').value;
var AbLadeValue = document.getElementById('wayp2').value;
var waypts = LadeValue + AbLadeValue;
但它不起作用。有没有解决这个问题的答案?
是否有可能获得总和的完整距离?现在,输出给出了每条路线的距离
(start->waypoint 1->waypoint 2->end).
提前致谢
答案 0 :(得分:0)
DirectionsRequest
对象waypoints
属性必须是数组。
var waypts = LadeValue + AbLadeValue;
上面代码的作用就是将2个字符串连接成一个字符串。一个非常简单的console.log(waypts)
可以帮助解决这个问题。
如果输入的纬度为10
且经度为20
,则上述内容将记录1020
。
var waypts = [LadeValue, AbLadeValue]; // This is an array