I am using the react-google-maps/api
library. I have an array with 8 locations and I am displaying different custom svg markers on all those locations. Till here all works great. Now I am stuck with the implementation of infoWindow
on click of each marker. I tried to go through the documentation but never get get it right though.
import React from 'react'
import { GoogleMap, useJsApiLoader, OverlayView, InfoWindow } from '@react-google-maps/api';
const MapSearch = React.memo(({latitude, longtitude, locations}) =>{
const containerStyle = {
width: '100%',
height: '100%'
};
const center = {
lat: JSON.parse(latitude),
lng: JSON.parse(longtitude)
};
const options = {
streetViewControl: false,
fullscreenControl:false,
mapTypeControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
}
}
const { isLoaded } = useJsApiLoader({
id: 'google-map-script',
googleMapsApiKey: config.googleMapsApiKey
});
return(
isLoaded ? (
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={8}
options={options}
>
{ /* Child components, such as markers, info windows, etc. */ }
{locations &&
locations.map((marker, i) => {
return <OverlayView
position={{lat:marker.latitude, lng:marker.longitude}}
mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
>
<svg className='map-icon' width="44" height="64" viewBox="0 0 44 64" fill="none" xmlns="http://www.w3.org/2000/svg">
---- Path not putting here to avoid code length -----
</svg>
</OverlayView>
})
}
</GoogleMap>
) : <></>
)
});
export default React.memo(MapSearch)
Try to use this way
import { InfoWindow, Marker } from '@react-google-maps/api';
const [infoWindowOpen, setInfoWindowOpen] = useState(false);
const showInfoWindow = () => {
setInfoWindowOpen(true);
};
return (
<Marker
title='Marker Name'
position={{lat:marker.latitude, lng:marker.longitude}}
icon={markerIcon}
onClick={showInfoWindow}
>
{infoWindowOpen && (
<InfoWindow onCloseClick={() => setInfoWindowOpen(false)}>
<h1>Hi I am Info Window</h1>
</InfoWindow>
)}
</Marker>
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.