我有一个数据数组,我正在循环运行该数据数组,以生成从起点到终点的多条路线。
但是,当我添加“旅行模式”下拉菜单并加载时,路线的折线彼此重叠。
它可以与单个数据源一起正常工作,但是在循环中,有点bug。
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<div id="map"></div>
<script src="js/jquery.min.js"></script>
<script>
var data,directionsDisplay,directionsService,map;
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: 37.77, lng: -122.447}
});
directionsDisplay.setMap(map);
data = {
"0": {"startPoint":"25.220108, 55.282903","endPoint":"25.198466, 55.279945"},
"1": {"startPoint":"25.187760, 55.246509","endPoint":"25.198466, 55.279945"},
"2": {"startPoint":"25.170536, 55.255897","endPoint":"25.198466, 55.279945"},
};
calculateAndDisplayRoute(data,directionsService,directionsDisplay);
$('#mode').on('change',function(e){
//console.log($(this).val());
var selTravelMode = $(this).val();
calculateAndDisplayRoute(data,directionsService,directionsDisplay,selTravelMode);
});
}
function calculateAndDisplayRoute(data,directionsService,directionsDisplay,selTravelMode = 'DRIVING') {
$.each(data,function(i,dt){
directionsService.route({
origin: dt.startPoint,// data[0].startPoint,
destination: dt.endPoint, // data[0].endPoint,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selTravelMode]
}, function(response, status) {
if (status == 'OK') {
var directionsDisplay1 = new google.maps.DirectionsRenderer({
map: map,
});
directionsDisplay1.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIz...XXXX&callback=initMap">
</script>