Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Mon Apr 10 2023

Get users location using the Geolocation API in JavaScript

I have just published our first open source project on npmjs. It is a simple weather widget that you can check out on our open source page.

When I created it, I had the need of getting the current position of the user to show the correct weather from the city that the user is located in - hence, I used the built in Geolocation API in JavaScript. In todays example, I will share how we can retrieve the coordinates from the browser, and display them in a React component.

Some notes

  • In order to get the coordinates, the user must accept the browser to share the location, otherwise it will not work.
  • Most of the browsers have full support for it, but there are some exceptions. Check here for all infomation needed.

Implementation

In this guide we will use the getCurrentPosition() function that will give us back the coordinates.

Usage

It requires a callback function that will be triggered once the position is retrieved. And it is in the callback function that we can perform our magic.

navigator.geolocation.getCurrentPosition((position) => { console.log(position); });

Create a simple <Location> component

We will create a simple component that will display the latitude and longitude if we can access them (remember that the permissions must be accepted by the user).

import { useEffect, useState } from "react"; export const Location = () => { const [coordinates, setCoordinates] = useState({}); useEffect(() => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { setCoordinates({ latitude: position.coords.latitude, longitude: position.coords.longitude, }); }); } else { console.error("Geolocation is not supported by this browser"); } }, []); if (!coordinates.latitude || !coordinates.longitude) { return null; } return ( <div style={{ display: "flex", flexDirection: "column" }}> <span>{`Latitude: ${coordinates.latitude}`}</span> <span>{`Longitude: ${coordinates.longitude}`}</span> </div> ); };

When the component is mounted, we will first check that the geolocation API is supported by the browser, if so, we will try to get them. If found, we will print them.

Render it like

import { Location } from "./Location"; <Location />;

And now you should see some coordinates on the screen!

Outro

When I come across these small problems that we might not just now in our heads, I write a guide on it, and hopefully it can help someone out there in need of fast access to whatever problem lies ahead.

I hope you found this example helpful. All the best!

signatureMon Apr 10 2023
See all our articles