romich
@romich
Frontend разработчик

Как правильно удалить маршруты с google map при построении новых?

Суть в том, что при изменении выбора одного из радиобатонов (для изменения типа движения) не удаляются маршруты, а просто рисуются новые.

const directionsService = new google.maps.DirectionsService();
    const directionsDisplay = new google.maps.DirectionsRenderer();
    let selectedMode; // переменная мода маршрута

    function checkActiveTravelMode() {
      const inp = document.getElementsByName('travelmode');
      for (let i = 0; i < inp.length; i++) {
        if (inp[i].checked) {
          const id = inp[i].getAttribute('id');
          selectedMode = id.toUpperCase();
        }
      }
    }

    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
      checkActiveTravelMode();
      directionsService.route({
        origin: { placeId: start },
        destination: { placeId: end },
        travelMode: google.maps.TravelMode[selectedMode],
        transitOptions: {
          modes: ['BUS', 'RAIL', 'SUBWAY', 'TRAIN', 'TRAM'],
          routingPreference: 'FEWER_TRANSFERS',
        },
        provideRouteAlternatives: true,
      }, function (response, status) {

        directionsDisplay.setMap(null); // здесь пытаюсь очистить маршруты, но ни разу..

        if (status === 'OK') {
          const colors = ['blue', 'red', 'green', 'orange', 'yellow', 'black'];
          const responseRoutes = response.routes;
          for (let i = 0; i < responseRoutes.length; i++) {
            new google.maps.DirectionsRenderer({ // создаем новый объект, который потом не удаляется
              map: map,
              directions: response,
              routeIndex: i,
              polylineOptions: {
                strokeColor: colors[i],
                strokeWeight: 4,
                strokeOpacity: 0.5,
              },
            });
          }
        }
      });
    }

    function addPointRoute(el) {
      el.addListener('places_changed', function() {
        const places = el.getPlaces();

        if (places.length === 0) {
          return;
        }

        if (el === searchFrom) {
          start = places[0].place_id || '';
        } else {
          end = places[0].place_id || '';
        }

        if (start && end) {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        }
      });
    }

    addPointRoute(searchFrom);
    addPointRoute(searchTo);

    for (let i = 0; i < modesItem.length; i++) {
      modesItem[i].addEventListener('click', function () {
        calculateAndDisplayRoute(directionsService, directionsDisplay); // запускаем функции при изменении мода маршрута
      });
    }
  • Вопрос задан
  • 590 просмотров
Пригласить эксперта
Ответы на вопрос 1
romich
@romich Автор вопроса
Frontend разработчик
Итого, в итоге рабочий вариант у меня
Нужно создавать в глобальной зоне видимости массив, куда кладем маршруты. А потом их очищаем каждый раз при вызове.
const directionsService = new google.maps.DirectionsService;
const directionsDisplay = new google.maps.DirectionsRenderer;
let directions = [];

() => {
directionsService,
if (status === 'OK') {
          const colors = ['blue', 'red', 'green', 'orange', 'yellow', 'black'];
          const responseRoutes = result.routes;

          directions.forEach((direction) => {
            direction.setMap(null);
          });

          directions = [];

          for (let i = 0; i < responseRoutes.length; i++) {
            const directionsOptions = {
              directions: result,
              routeIndex: i,
              polylineOptions: {
                strokeColor: colors[i],
                strokeWeight: 4,
                strokeOpacity: 0.5,
              },
            };
            const newDirection = new google.maps.DirectionsRenderer(directionsOptions);
            newDirection.setMap(map);
            directions.push(newDirection);
          }
      }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы