Почему я не могу удалить Маркеры Google? - PullRequest
1 голос
/ 25 апреля 2020

У меня есть методы рендеринга маркеров, как показано ниже. Я передаю массив маркеров из реквизита и отрисовываю его каждый раз, когда запускается componentDidUpdate. Проблема в том, что мои старые маркеры не удаляются с карт. Например, если у меня есть 1 координата внутри моего родительского компонента и я обновляю его новыми, появляется новая, а старая стоит на месте.

`
import React from 'react';

const google = window.google;

export class GMap extends React.Component {
  mapRef = React.createRef();
  directionsService
  directionsRenderer
  map;

  componentDidMount() {
    this.initMap();
    const { onClick } = this.props;

    onClick && this.onMapClick();
  }

  componentDidUpdate() {
    const { markers } = this.props;

    this.calcRoute();
    if (markers && markers.length > 0) {
        this.clear(markers);
        this.renderMarkers(markers);
    }
  }

  initMap() {
    this.directionsService = new google.maps.DirectionsService();
    this.directionsRenderer = new google.maps.DirectionsRenderer();
    const mapOptions = {
        zoom: 13,
        center: { lat: 40.386119, lng: 49.860925 }
    }
    const map = new google.maps.Map(document.getElementById('map'), mapOptions);
    this.map = map;
    this.directionsRenderer.setMap(map);
  }

  onMapClick() {
    this.map.addListener('click', (e) => {
        this.props.onClick(e);
    })
  }

  renderMarkers(markers) {
    markers.forEach(position => {
        const marker = new google.maps.Marker({ position });
        marker.setMap(this.map);
    })
  }



  calcRoute() {
    const { directions } = this.props;

    if (directions) {
        const [{ lat: fLat, lng: fLng }, { lat: tLat, lng: tLng }] = directions;

        if (fLat && fLng && tLat && tLng) {
            var request = {
                origin: { lat: fLat, lng: fLng },
                destination: { lat: tLat, lng: tLng },
                travelMode: 'DRIVING'
            };
            this.directionsService.route(request, (result, status) => {
                if (status === 'OK') {
                    this.directionsRenderer.setDirections(result);
                }
            });
        }
     }


  }

  render() {
    return (
        <div id='map' ref={this.mapRef} />
    )
  }

}

`

1 Ответ

0 голосов
/ 28 апреля 2020

Как вы убираете маркеры? Все, что я вижу в размещенном коде, это this.clear(markers) без ссылки на clear. Попробуйте сделать что-то вроде этого:

clear(markers) {
  for(let i = 0; i < markers.length; i++) {
     markers[i].setMap(null);
  }
}

Надеюсь, это поможет!

...