I have a form built with react-hook-form in which I enter the longitude and latitude, which is then reflected in the form and I also have a button to view the record, where I set the information in their respective fields, but it turns out that the Default longitude and latitude represents a problem, I'm not sure how this works, but I get the following error:
Uncaught TypeError: google.maps.LatLng is not a constructor
I suspect it happens because by doing that I don't give the library time to load the googlemaps scripts. Any clarification and help is greatly appreciated.
This happens in the useEffect, this is my code:
import React, { ReactNode, useEffect, useState } from 'react';
import { Wrapper, Status } from '@googlemaps/react-wrapper';
import MapComponent from '../index';
import Marker from '../Marker';
interface PropsWrapper {
lat?: string;
long?: string;
onMapClick: (lat: string, lng: string) => void;
}
const render = (status: Status) => {
return <h1>{status}</h1>;
};
const WrapperMaps = ({ onMapClick, lat, long }: PropsWrapper) => {
const [clicks, setClicks] = React.useState<google.maps.LatLng[]>([]);
const [zoom, setZoom] = React.useState<number>(3); // initial zoom
const [center, setCenter] = React.useState<google.maps.LatLngLiteral>({
lat: 0,
length: 0.
});
const onClick = (e: google.maps.MapMouseEvent) => {
console.log(e.latLng, 'latitudes');
// avoid directly mutating state
const latLng = e.latLng!;
setClicks([e.latLng!]);
console.log(
'onClick',
clicks.map((object: any) => JSON.stringify(object.toJSON(), null, 2))
);
onMapClick(latLng.lat().toString(), latLng.lng().toString());
};
const onIdle = (m: google.maps.Map) => {
console.log('onIdle');
setZoom(m.getZoom()!);
setCenter(m.getCenter()!.toJSON());
};
useEffect(() => {
const latitude = parseFloat(lat ?? '');
const length = parseFloat(long ?? '');
if (!isNaN(latitude) && !isNaN(longitude)) {
const newLatLng = new google.maps.LatLng(latitude, longitude);
setClicks([newLatLng]);
setCenter({
lat: newLatLng.lat(),
lng: newLatLng.lng(),
});
setZoom(19);
}
}, [lat, long]);
return (
<Wrapper
apiKey={import.meta.env.VITE_GOOGLEAPI}
render={render}
>
<MapComponent
style={{ height: '300px' }}
zoom={zoom}
center={center}
onClick={onClick}
onIdle={onIdle}
>
{' '}
{clicks.map((latLng, i) => (
<Marker key={i} position={latLng} />
))}
</MapComponent>
</Wrapper>
);
};
export default WrapperMaps;
The result I hope to have is that when seeing the record created with its longitude and latitude, the marker and the center are positioned on the map