I am trying to center the map in the geoposition and I get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'coords')
If I console log the position in the getLocationHandler, the object seems to have the coordinates.
import GoogleMapReact from "google-map-react";
import { Geolocation } from "@ionic-native/geolocation";
import { IonLoading } from "@ionic/react";
const Map = (props) => {
const [isLoading, setIsLoading] = useState(false);
const [position, setPosition] = useState();
const getLocationHandler = async () => {
try {
setIsLoading(true);
const position = await Geolocation.getCurrentPosition();
setPosition(position);
} catch (e) {}
setIsLoading(false);
};
useEffect(() => {
getLocationHandler();
}, []);
return (
<>
<IonLoading
isOpen={isLoading}
message={"Getting Location..."}
onDidDismiss={() => setIsLoading(false)}
></IonLoading>
<div className="map">
<div className="google-map" style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{ key: .... }}
defaultCenter={
{
lat: position.coords.latitude,
lng: position.coords.longitude,
}
}
defaultZoom={11}>
</GoogleMapReact>
</div>
</div>
</>
);
};
export default Map;
CodePudding user response:
On your first render, position
will be undefined so when you're trying to use position.coords.latitude
it's throwing that error. I would probably leverage your isLoading
state and only render the second part of your component when that is false -
<div className="google-map" style={{ height: "100vh", width: "100%" }}>
{!isLoading && (
<GoogleMapReact
...etc
)}
</div>
Also, it would probably make sense to set the initial value of isLoading
to true instead of manually setting that to true inside your async loading function.
Alternatively, instead of checking isLoading
you could directly check position?.coords?.latitude