Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undefined (reading 'coords') using @ionic-native/geolocation – ionic / react

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading