I am trying to achieve a map interface in React. When the user clicks on the map. The marker must get display in that particular coordinates.
import GoogleMapReact from "google-map-react";
import marker from "../../Assets/marker.png";
const [GmapKey, setGmapKey] = useState("");
const [selectedLocation, setSelectedLocation] = useState(null);
const [zoom, setZoom] = useState(4);
const [center, setCenter] = useState({
lat: 20.5937,
lng: 78.9629,
});
const defaultProps = {
center: {
lat: 20.5937,
lng: 78.9629,
},
zoom: 4,
};
const [item, setItem] = useState({
productName: "",
days: "",
price: "",
image: "",
state: "",
pincode: "",
lati: "",
longi: "",
city: "",
});
These are the state variables which are being used
useEffect(() => {
const fetchLatlongByPincode = async () => {
try {
const response = await axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?address=${item?.pincode}&key=${GmapKey}`
);
const { lat, lng } = response.data.results[0]?.geometry?.location;
setCenter({ ...center, lat, lng });
setZoom(8);
setSelectedLocation({ lat, lng });
setItem({ ...item, lati: lat, longi: lng });
} catch (error) {
console.error("Error fetching lat long:", error);
}
};
if (item?.pincode?.length === 6) {
fetchLatlongByPincode();
}
}, [item.pincode, GmapKey]);
const handleMapClick = ({ lat, lng }) => {
setSelectedLocation({ lat, lng });
setZoom(6)
setItem({ ...item, lati: lat, longi: lng });
};
These Are the Functions which get triggered on Map Click or When the pincode value will be changed
I am currently trying using
{GmapKey && (
<div
className="form-group py-6"
style={{ width: "100%", height: "400px" }}
>
<label htmlFor="location" className={styles.label}>
Location
</label>
<GoogleMapReact
onClick={handleMapClick}
bootstrapURLKeys={{ key: GmapKey.toString() }}
defaultCenter={defaultProps.center}
defaultZoom={defaultProps.zoom}
center={center}
zoom={zoom}
>
{/* Marker */}
{selectedLocation && (
<div
style={{ position: "relative" }}
lat={selectedLocation?.lat}
lng={selectedLocation?.lng}
>
<img src={marker} alt="mapmarker" className="w-[25px] relative z-50" />
</div>
)}
</GoogleMapReact>
</div>
)}
My Map Functionality and Zoom functionality is being Triggered also the latitude and longitude are being set by api. Only issue with the marker being displayed

