-
-
Save alpezed/51e376b5cd835df56ad9d383b9c8f1f2 to your computer and use it in GitHub Desktop.
React google maps with multiple markers, only one info window
This file contains hidden or 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