I'm using the @googlemaps/js-api-loader package to load a map in my nextJS app. I have a list of locations that I want to plot on the map, and I also want these locations disabled on the left side of the page.
When hovering over one of the locations in the list, I want to dynamically change the color of the marker representing that location, similar to how the current focus works on the map. How can I achieve this?
This is what my code looks like:
type MarkerObject = {
id: number
marker: google.maps.marker.AdvancedMarkerElement
}
export const MapComponent = ({ locations, currentFocusId }: MapProps) => {
const [markers, setMarkers] = useState<MarkerObject[]>([])
useEffect(() => {
const initMap = async () => {
const loader = new Loader({ apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY! })
const { Map } = (await loader.importLibrary('maps')) as google.maps.MapsLibrary
// create map
const map = new Map(document.getElementById('map') as HTMLElement, {
center: locations[0].position,
zoom: 15,
mapId: 'map',
})
// create markers
for (const location of locations) {
const pinBackground = new PinElement({
borderColor: 'black',
glyphColor: 'black',
})
const marker = new AdvancedMarkerElement({
map,
position: location.position,
content: pinBackground.element,
})
setMarkers((prev) => [...prev, { id: location.id, marker }])
}
}
initMap()
}, [])
useEffect(() => {
if (!markers.length) return
const focusMarker = markers.find((markerObject: MarkerObject) => markerObject.id === currentFocusId)
if (!focusMarker) return
// How can I change or replace the content/color of the marker to make it blue?
I have attempted things such as
focusMarker.marker.content = new google.maps.marker.PinElement({
background: 'blue',
borderColor: 'black',
glyphColor: 'black',
})
but I haven't had any success yet.