Search code examples
reactjsgoogle-maps-api-3google-maps-markersreact-google-maps

Set marker on react-google-maps when user clicks on map


I want to set multiple markers on google maps whenever any user clicking on any location in the map. I am using functional approach in my react app.

                     <LoadScript googleMapsApiKey={mapKey}>
                     <GoogleMap
                     mapContainerStyle={{
                     width: '100%',
                     height: '85vh',
                     }}
                     center={center}
                     zoom={19}
                     onClick={ev => {
                     console.log("latitide = ", ev.latLng.lat());
                     console.log("longitude = ", ev.latLng.lng());
                      }}>
                    
 
                     <Polyline
                     path={trucks}
                     geodesic={true}
                     options=
                     {{
                     strokeColor: "blue",
                     strokeOpacity: 5,
                     strokeWeight: 4,
                     }}
             />
              {trucks?.map((d, i) => (
                     <MarkerF key={i} 
                     onLoad={onLoad} 
                     position={d} />
                     ))}
                     </GoogleMap>
                     </LoadScript>
                 </div> ```

Solution

  • Here is how you can easily do this. You need to add a state for your markers and then on your onClick event call the setter such as this:

    [markers, setMarker] = useState([]);
    
    const onMapClick = (e) => {
        setMarkers((current) => [
          ...current,
          {
            lat: e.latLng.lat(),
            lng: e.latLng.lng()
          }
        ]);
      };
    
    

    The map with markers:

    <GoogleMap
      mapContainerStyle={{
        width: '100%',
        height: '85vh',
        }}
      center={center}
      zoom={19}
      onClick={onMapClick}
      >           
      
        {markers.map((marker) => (
            <Marker 
              position={{ 
                lat: marker.lat,
                lng: marker.lng 
              }} />
        ))}
    </GoogleMap>