Nicholas Mirabile
Nicholas Mirabile

Reputation: 13

How to modify/remove markers from React Google Maps package?

I am currently trying to make a map using the React Google Maps. Currently, I can plot the markers just fine but when I go to change them or remove them I run into problems where it only renders a gray screen. Is there a way to do this gracefully within the package?

Thanks

I have tried rerendering the map in a useeffect that triggers whenever the markers change but to no avail, it renders a gray screen. I would very much prefer not to wander outside this package and use the google maps markers and advanced markers and refs and all that if possible.

<Map
          key={`${mapState.center.lat}-${mapState.center.lng}-${mapState.zoom}`}
          defaultCenter={mapState.center}
          defaultZoom={mapState.zoom}
          gestureHandling={"greedy"}
          disableDefaultUI={true}
          mapId={process.env.NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID!}
        >
          {markers.map((marker, index) => (
            <CustomMarker
              key={index}
              marker={marker}
              onClick={() => setSelectedMarker(marker)}
            />
          ))}

Upvotes: 0

Views: 206

Answers (1)

Code on the Rocks
Code on the Rocks

Reputation: 17854

You can create a filtered list of markers like this and then loop through it.

let filteredMarkers = markers.filter((marker)=> marker.value > 5);

...

<Map
          key={`${mapState.center.lat}-${mapState.center.lng}-${mapState.zoom}`}
          defaultCenter={mapState.center}
          defaultZoom={mapState.zoom}
          gestureHandling={"greedy"}
          disableDefaultUI={true}
          mapId={process.env.NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID!}
        >
          {filteredMarkers.map((marker, index) => (
            <CustomMarker
              key={index}
              marker={marker}
              onClick={() => setSelectedMarker(marker)}
            />
          ))}
</Map>

If you are receiving a specific error when you remove a marker, please share that too.

Upvotes: 0

Related Questions