Jeevan Rupacha
Jeevan Rupacha

Reputation: 5856

Get geolocation coordinates [ latitude, longitude ] of current location in NextJS/ReactJS

I need the latitude, longitude of the current location of the user to show posts accordingly, I'm using next.js can anyone help me out?

Upvotes: 0

Views: 7079

Answers (2)

Jeevan Rupacha
Jeevan Rupacha

Reputation: 5856

I solve it by doing following :-

useEffect(()=> {
    navigator.geolocation.getCurrentPosition(function(position) {
      console.log("Latitude is :", position.coords.latitude);
      console.log("Longitude is :", position.coords.longitude);
    });
  })

Upvotes: 11

Ramakay
Ramakay

Reputation: 3145

use router.pathName - This provides the current path -

import { useRouter } from 'next/router'

const router = useRouter();

const currentPath = router.pathName

//...rest of your code

This ensures availability both via SSR and CSR

Ref: https://nextjs.org/docs/api-reference/next/router

Upvotes: -4

Related Questions