I'm using google map directions API, and I added functions that if you click each periods, it indicates route of each periods(for example, if you click '2021 Sep-2021 Oc', it shows routes from A-D. ). I'm using new google.maps.DirectionsRenderer() to render route.
And I want to delete the route if you click another period. For example, if you click '2021 Sep-2021 Oc', it shows routes from A-D. And after that, if you click '2021 Oc - 2021 Nov', it deletes route of '2021 Sep-2021 Oc', and shows route of '2021 Oc - 2021 Nov'.
How can I do that?
I tried
<pre lang="Javascript">
if(thisPeriod != index){
console.log(index)
directionsService.route( routeofThePeriod, function(result, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections({routes:[]});
}
})
}
and
if(thisPeriod != index){
directionsDisplay.setMap(null);
}
and
if(thisPeriod != index){
directionsDisplay.setOptions({
suppressPolylines: true,
})
directionsDisplay.setMap(map);
}
but none of them worked properly....
What I have tried:
<pre>
let periods = document.querySelectorAll('.period');
let periodArray = [
{
origin: new google.maps.LatLng(40.8020712, -124.1636729),
destination: new google.maps.LatLng(43.038902, -87.906471),
waypoints: [
{location: new google.maps.LatLng(29.4502321, -98.5169623)},
{location: new google.maps.LatLng(42.0039331, -83.9449417)},
],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
},
{
origin: new google.maps.LatLng(32.335251, -95.31025),
destination: new google.maps.LatLng(30.110495, -97.315269),
waypoints: [
{location: new google.maps.LatLng(32.550149,-94.3668628)},
{location: new google.maps.LatLng(40.044437,-76.306229)},
{location: new google.maps.LatLng(39.299236,-76.609383)},
],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
}
]
periods.forEach((period, index) => {
period.addEventListener('click', drawPolyline);
})
function drawPolyline(){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
let thisPeriod = `${this.id}`.slice(-1);
periodArray.forEach((routeofThePeriod, index) =>{
if(thisPeriod != index){
console.log(index)
directionsService.route( routeofThePeriod, function(result, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections({routes:[]});
}
})
}
else if(thisPeriod == index){
directionsDisplay.setMap(map);
directionsDisplay.setOptions({
suppressMarkers:true,
suppressInfoWindows: true,
suppressPolylines: false,
polylineOptions: {
strokeColor: 'red',
strokeOpcaity: 0.5,
strokeWeight: 5
}
})
directionsService.route( routeofThePeriod, function(result, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(result);
}
})
}
})
}