When Displaying Multiple Markers On A Map, How To Open Just One Info Window, When Clicking On A Marker?
I'm using react-google-maps to display a map with markers, and when you click on a marker, all the info windows open up. I would like to display only one marker's info window when
Solution 1:
It's more of a React
question. You can pass the index of a clicked Marker
to onToggleOpen
and instead of isOpen
you use a selectedPlace
state that holds the index of a clicked Marker
and use this index to render the right InfoWindow
.
Here is an example (not fully tested, but you can get the idea):
/*global google*/importReactfrom"react"import { compose, withProps, withHandlers, withState, withStateHandlers } from"recompose"import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from"react-google-maps"constMyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
loadingElement: <divstyle={{height: `100%` }} />,
containerElement: <divstyle={{height: `400px` }} />,
mapElement: <divstyle={{height: `100%` }} />,
}),
withScriptjs,
withGoogleMap,
withState('places', 'updatePlaces', ''),
withState('selectedPlace', 'updateSelectedPlace', null),
withHandlers(() => {
const refs = {
map: undefined,
}
return {
onMapMounted: () =>ref => {
refs.map = ref
},
fetchPlaces: ({ updatePlaces }) => {
let places;
const bounds = refs.map.getBounds();
const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
const request = {
bounds: bounds,
type: ['hotel']
};
service.nearbySearch(request, (results, status) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results);
updatePlaces(results);
}
})
},
onToggleOpen: ({ updateSelectedPlace }) =>key => {
updateSelectedPlace(key);
}
}
}),
)((props) => {
console.log(props);
return (
<GoogleMaponTilesLoaded={props.fetchPlaces}ref={props.onMapMounted}onBoundsChanged={props.fetchPlaces}defaultZoom={15}defaultCenter={{lat:51.508530, lng:-0.076132 }}
>
{props.places && props.places.map((place, i) =>
<MarkeronClick={() => props.onToggleOpen(i)} key={i} position={{ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }}>
{props.selectedPlace === i && <InfoWindowonCloseClick={props.onToggleOpen}><div>
{props.places[props.selectedPlace].name}
</div></InfoWindow>}
</Marker>
)}
</GoogleMap>
)
})
exportdefaultclassMyFancyComponentextendsReact.PureComponent {
render() {
return (
<MyMapComponent />
)
}
}
Post a Comment for "When Displaying Multiple Markers On A Map, How To Open Just One Info Window, When Clicking On A Marker?"