Skip to content

Instantly share code, notes, and snippets.

@jwo
Last active March 31, 2022 10:41
Show Gist options
  • Save jwo/43b382fc60eb09d3a415c9953f4057f8 to your computer and use it in GitHub Desktop.
Save jwo/43b382fc60eb09d3a415c9953f4057f8 to your computer and use it in GitHub Desktop.
React google maps with multiple markers, only one info window
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%` }} />}
/>
)
}
}
@tiwari4github
Copy link

Hi @nik

Hii , while working with Mapbox why its showing markers at only in one map

Hi i am trying to render markers on Mapbox, but unable to do so , can you provide me any idea about that?

@doums10
Copy link

doums10 commented Oct 6, 2021

Do you know how to add a mouseover event on the marker to have the infowindow ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment