Categories
JavaScript React

How to Get a User’s Location with the Navigator API

Getting a user’s location enables you to do things like show it on a map, provide information about the location, serve up personalised content, and more.

Getting that initial geolocation data is probably easier than you think.

Vanilla Javascript

geolocation is part of the Navigator interface (or Web API). Getting the user’s location is as simple as calling the getCurrentPosition() method like below.

const getGeolocation = () => {
  navigator.geolocation.getCurrentPosition((pos) => {
    console.log(pos);
  });
};

React Functional Component

Below is a slightly extended version of the example above, built in React, which stores the individual pieces of data that getCurrentPosition() returns and prints it to the DOM.

import { Fragment, useState } from "react";

const NavigatorExample = () => {
  const [pos, setPos] = useState({});

  const getGeolocation = () => {
    navigator.geolocation.getCurrentPosition((position) => {
      setPos({
        timestamp: position.timestamp,
        accuracy: position.coords.accuracy,
        altitude: position.coords.altitude,
        altitudeAccuracy: position.coords.altitudeAccuracy,
        heading: position.coords.heading,
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        speed: position.coords.speed,
      });
    });
  };

  return (
    <Fragment>
      <h2>Navigator API Example</h2>
      <button onClick={() => getGeolocation()}>
        Get & display geolocation
      </button>
      <ul>
        {Object.keys(pos).map((key) => (
          <li key={key}>
            {key}: {pos[key]}
          </li>
        ))}
      </ul>
    </Fragment>
  );
};

export default NavigatorExample;

Leave a Reply

Your email address will not be published.