我想在React.js的谷歌地图项目中关闭infowindow,但它现在正在工作。 infowindow.open()似乎工作正常。我试图在我的过滤器函数中关闭infowindow,但我一直得到infowindow.close()不是函数。
如何将componentsDidMount函数中的infowindow调用到我的过滤函数中?
这是我的代码
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***
答案 0 :(得分:0)
您在调用open之前声明了一个新的const infowindow,一旦到达您调用.close()的行,就不再在范围内了。而且我不知道infowindow.close()是否在你的MapContainer类中,但你可以在顶部声明一个var infowindow,那么你的行是infowowowow = new google.maps.InfoWindow()只是变成infowindow = new google .maps.InfoWindow()