infowindow.close () не работает на картах Google с помощьюactjs - PullRequest
0 голосов
/ 28 мая 2018

Я пытаюсь закрыть информационное окно в своем проекте карт Google в React.js, но теперь оно работает.infowindow.open (), кажется, работает нормально.Я пытаюсь закрыть информационное окно в моей функции фильтра, но получаю, что infowindow.close () не является функцией.

Как мне вызвать информационное окно в функции componentDidMount для моей функции фильтра?

Это мой код

export default class MapContainer extends Component {
// ======================
// ADD LOCATIONS TO STATE
// ======================
constructor(props) {
super(props)
this.state = {
    places: [],
    filtered: [],
    search: ''

}
}
 componentDidMount() {

if (this.props && this.props.google) { // checks to make sure that props have 
  been passed
    const {
        google,
        infowindow
    } = this.props; // sets props equal to google
    const maps = google.maps; // sets maps to google maps props

    const mapRef = this.refs.map; // looks for HTML div ref 'map'. Returned in render below.
    const node = ReactDOM.findDOMNode(mapRef); // finds the 'map' div in the React DOM, names it node

    const mapConfig = Object.assign({}, {
        center: {
            lat: 51.0486,
            lng: -114.0708
        }, // sets center of google map to NYC.
        zoom: 11, // sets zoom. Lower numbers are zoomed further out.
        mapTypeId: 'roadmap' // optional main map layer. Terrain, satellite, hybrid or roadmap--if unspecified, defaults to roadmap.
    })

    this.map = new maps.Map(node, mapConfig); // creates a new Google map on the specified node (ref='map') with the specified configuration set above.

    // ==================
    // ADD MARKERS TO MAP
    // ==================

    zomatoAPI()
        .then(p => {
                this.setState({
                    places: p,
                    filtered: p
                })
                const {
                    google,
                    infowindow
                } = this.props;
                p.forEach(location => { // iterate through locations saved in state
                    location.marker = new google.maps.Marker({ // creates a new Google maps Marker object.
                        position: {
                            lat: Number(location.location.latitude),
                            lng: Number(location.location.longitude)
                        }, // sets position of marker to specified location
                        map: this.map, // sets markers to appear on the map we 
  just created on line 35
                        title: location.name // the title of the marker is set 
    to the name of the location
                    });

                    location.marker.addListener('click', function () {

                        const content =
                            `<div class="place">
                          <img height= 70px width=70px src=${this.photo} 
      alt="${this.title}">

                            <h3>${this.title}</h3>
                            <p>Cuisine: ${this.cuisines}</p>
                            <p>Rating: ${this.rateText}, ${this.rating}</p>
                            <p>Price: ${this.price}</p>

                            `


                        const infowindow = new google.maps.InfoWindow()

                        infowindow.setContent(content)


                        infowindow.open(this.map, this)

                    })
                })

            }

        )
}

     }
    filter = (e) => {
    const {
    google, infowindow
} = this.props
const {
    places,
    filtered
} = this.state;
const search = e.target.value;


this.setState({
    search: search
})
infowindow.close()   //==================>>>>>> ****issue***

1 Ответ

0 голосов
/ 29 мая 2018

Вы объявляете новое const информационное окно перед вызовом open, которое больше не находится в области действия, как только вы достигнете строки, где вы вызываете .close ().И я не могу сказать, находится ли infowindow.close () внутри вашего класса MapContainer, но вы можете объявить var infowindow вверху, тогда ваша строка const infowindow = new google.maps.InfoWindow () просто станет infowindow = new google.maps.InfoWindow ()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...