1.0.5 ⢠Published 5 months ago
current-geo-location v1.0.5
geo-location-ip
A Get-location NPM package to fetch user country , countryCode , stateCode , state , city, zip , latitude , longitude , timezone details .
š¦ Installation
Install the package using npm:
npm install current-geo-location
Or using yarn:
yarn add current-geo-location
š Usage
ā
Method 1: Using Destructuring
const getUserLocation = require("current-geo-location");
getUserLocation()
.then(({ country, countryCode, stateCode, state, city, zip, latitude, longitude, timezone }) => {
console.log({ country, countryCode, stateCode, state, city, zip, latitude, longitude, timezone });
})
.catch(console.error);
ā
Method 2: Using Direct Response
const getUserLocation = require("current-geo-location");
getUserLocation()
.then((response) => {
console.log(response); // Logs full object
})
.catch(console.error);
ā
Method 3 : Using React functional component
import React, { useState, useEffect } from "react";
import getUserLocation from "current-geo-location";
const LocationComponent = () => {
const [location, setLocation] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
getUserLocation()
.then(setLocation) // Stores the data in state
.catch(setError); // Handles errors
}, []);
if (error) return <p>Error: {error.message}</p>;
if (!location) return <p>Loading location...</p>;
return (
<div>
<h2>Your Location</h2>
<p><strong>Country:</strong> {location.country} ({location.countryCode})</p>
<p><strong>State:</strong> {location.state} ({location.stateCode})</p>
<p><strong>City:</strong> {location.city}</p>
<p><strong>ZIP Code:</strong> {location.zip}</p>
<p><strong>Latitude:</strong> {location.latitude}</p>
<p><strong>Longitude:</strong> {location.longitude}</p>
<p><strong>Timezone:</strong> {location.timezone}</p>
</div>
);
};
export default LocationComponent;
š Returned Object Example
{
"country": "United States",
"countryCode": "US",
"stateCode": "CA",
"state": "California",
"city": "Los Angeles",
"zip": "90001",
"latitude": 34.0522,
"longitude": -118.2437,
"timezone": "America/Los_Angeles"
}
š License
This project is licensed under the MIT License.