Last active
March 31, 2022 10:41
-
-
Save jwo/43b382fc60eb09d3a415c9953f4057f8 to your computer and use it in GitHub Desktop.
React google maps with multiple markers, only one info window
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react" | |
import { compose } from "recompose" | |
import { | |
withScriptjs, | |
withGoogleMap, | |
GoogleMap, | |
Marker, | |
InfoWindow | |
} from "react-google-maps" | |
const MapWithAMarker = compose(withScriptjs, withGoogleMap)(props => { | |
return ( | |
<GoogleMap defaultZoom={8} defaultCenter={{ lat: 29.5, lng: -95 }}> | |
{props.markers.map(marker => { | |
const onClick = props.onClick.bind(this, marker) | |
return ( | |
<Marker | |
key={marker.id} | |
onClick={onClick} | |
position={{ lat: marker.latitude, lng: marker.longitude }} | |
> | |
{props.selectedMarker === marker && | |
<InfoWindow> | |
<div> | |
{marker.shelter} | |
</div> | |
</InfoWindow>} | |
} | |
</Marker> | |
) | |
})} | |
</GoogleMap> | |
) | |
}) | |
export default class ShelterMap extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
shelters: [], | |
selectedMarker: false | |
} | |
} | |
componentDidMount() { | |
fetch("https://api.harveyneeds.org/api/v1/shelters?limit=20") | |
.then(r => r.json()) | |
.then(data => { | |
this.setState({ shelters: data.shelters }) | |
}) | |
} | |
handleClick = (marker, event) => { | |
// console.log({ marker }) | |
this.setState({ selectedMarker: marker }) | |
} | |
render() { | |
return ( | |
<MapWithAMarker | |
selectedMarker={this.state.selectedMarker} | |
markers={this.state.shelters} | |
onClick={this.handleClick} | |
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places" | |
loadingElement={<div style={{ height: `100%` }} />} | |
containerElement={<div style={{ height: `400px` }} />} | |
mapElement={<div style={{ height: `100%` }} />} | |
/> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you know how to add a mouseover event on the marker to have the infowindow ?