I am building a react application where a user can add markers to a GoogleMaps map by clicking on it. The problem is, when I click the map, the point is added to the array, but the marker is not rendered.For some reason, and the function inside the map is only called once, when the map is firstly displayed.
import { useAuth } from "../contexts/AuthContext";
import Navbar from "./Navbar";
import { useJsApiLoader, GoogleMap, Marker } from '@react-google-maps/api'
import { Box } from '@chakra-ui/react';
import { useState } from 'react';
import LoadingCircle from "./LoadingCircle";
export default function MapPage() {
const center = { lat: 50.45, lng: 30.52 };
const { loading, currentUser } = useAuth();
const { isLoaded } = useJsApiLoader({
googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
libraries: ['places']
});
const [map, setMap] = useState(null);
const [points, setPoints] = useState([center]);
console.log(process.env.REACT_APP_GOOGLE_MAPS_API_KEY)
if (!isLoaded) {
return (
<div>
<Navbar></Navbar>
<LoadingCircle />
</div>
);
}
return (
<div>
<Navbar></Navbar>
<div className="">
<Box position={'relative'} top={0} left={0} h="93.5vh" w="100%" className="h-full w-full">
<GoogleMap
center={center}
zoom={15}
mapContainerStyle={{ width: '100%', height: '100%' }}
options={{
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false,
}}
onLoad={(map) => setMap(map)}
onClick={e => {
let lat = e.latLng.lat();
let lng = e.latLng.lng();
let new_point = { lat: lat, lng: lng };
let new_points = points;
new_points.push(new_point);
setPoints(new_points);
setMap(map);
console.log(points);
}}>
{
points.map((point, index) => {
console.log(point);
console.log(index);
return <Marker position={point}/>
})
}
</GoogleMap>
</Box>
</div>
</div>
);
}