我需要爲我的地圖中的每個標記創建一個信息窗口。我可以在地圖上看到標記,但當我點擊標記以獲取InfoWindow時,出現TypeError: Cannot read property 'isOpen' of undefined
錯誤,參考this.setState({isOpen: !this.state.isOpen})
中的onToggleOpen
。react-google-maps多個標記和信息窗口
感謝代表
componentWillMount() {
this.setState({ markers: [], isOpen: false })
}
componentDidMount() {
let list = { restaurants : []}
database.ref('..').on('value', .. => {
...
})
this.setState({ markers: list.restaurants});
})
}
onToggleOpen(){
this.setState({isOpen: !this.state.isOpen})
}
render() {
const MapWithAMarker = compose(
withProps({
googleMapURL: ...,
loadingElement: ...,
containerElement: ...,
mapElement: ...
}),
withScriptjs,
withGoogleMap
)(props =>
<GoogleMap
defaultZoom={17}
defaultCenter={{ lat: ..., lng: ... }}
>
{props.markers.map(marker => (
<Marker
key={marker.name}
position={{ lat: marker.latitude, lng: marker.longitude }}
onClick={this.onToggleOpen}
>
{this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}> marker.key </InfoWindow>}
</Marker>
))}
</GoogleMap>
);
return (
<section id="mapa">
<div class= "container">
<div class="row">
<div class="col-md-12 text-left">
<h2 class="section-heading">MAPA</h2>
<MapWithAMarker markers={this.state.markers}/>
</div>
</div>
<div class="row text-center">
</div>
</div>
</section>
)
}
編輯:更新後的代碼:
export default class Mapa extends Component {
constructor(props) {
super(props)
this.state = {
markers: [],
isOpen: false
}
}
componentDidMount() {
let list = { restaurants : []}
database.ref('..').on('value', restaurants => {
restaurants.forEach(restaurant => {
list.restaurants.push({'name': restaurant.key,
'longitude': restaurant.val().lng,
'latitude': restaurant.val().lat}
)
})
this.setState({ markers: list.restaurants });
})
}
onToggleOpen =() => {
this.setState({isOpen: !this.state.isOpen})
}
render() {
const MapWithAMarker = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=...&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props =>
<GoogleMap
defaultZoom={17}
defaultCenter={{ lat: .., lng: ... }}
>
{props.markers.map(marker => (
<Marker
key={marker.name}
position={{ lat: marker.latitude, lng: marker.longitude }}
onClick={this.onToggleOpen}
>
{this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}> marker.key </InfoWindow>}
</Marker>
))}
</GoogleMap>
);
return (
<section id="mapa">
<div class= "container">
<h3 class="info-title"><span class="info-title-span">Tasty and Convenient.</span></h3>
<div class="row">
<div class="col-md-12 text-left">
<MapWithAMarker markers={this.state.markers}/>
</div>
</div>
<div class="row text-center">
</div>
</div>
</section>
)
}
就本聲明的渲染方法,所以它的範圍從那裏調用它:'VAR ISOPEN = this.state.isOpen;' – fungusanthrax