Skip to content

A lightweight TypeScript utility to fetch user's geolocation (latitude, longitude, accuracy) using the browser's native Geolocation API. Simple, Promise-based, and ideal for modern frontend apps.

Notifications You must be signed in to change notification settings

0501guptanitin/typescript-geolocation-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 

Repository files navigation

πŸ“ Get Geolocation Data in the Browser (TypeScript Utility)

This utility provides a simple, Promise-based way to access the user's geolocation in the browser using the Geolocation API, written in TypeScript.


✨ Features

  • βœ… Promise-based API
  • 🌐 Retrieves latitude, longitude, and accuracy
  • πŸ” Graceful fallback if geolocation is not supported
  • βš™οΈ Customizable options like high accuracy, timeout, and max age

πŸ“¦ Usage

1. Import and Call the Function

import { getGeolocationData } from './utils/geolocation';

getGeolocationData()
  .then((location) => {
    console.log('Location data:', location);
  })
  .catch((error) => {
    console.error('Geolocation error:', error.message);
  });

πŸ” Full Source Code

interface GeolocationResponse {
    latitude: number;
    longitude: number;
    accuracy: number;
}

export const getGeolocationData = (): Promise<GeolocationResponse> => {
    return new Promise((resolve, reject) => {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const locationData: GeolocationResponse = {
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        accuracy: position.coords.accuracy
                    };
                    resolve(locationData);
                },
                (error) => {
                    reject(new Error(`Geolocation error: ${error.message}`));
                },
                {
                    enableHighAccuracy: true,
                    timeout: 5000,
                    maximumAge: 0
                }
            );
        } else {
            reject(new Error("Geolocation is not supported by this browser."));
        }
    });
}

🚫 Fallback Handling

If the browser does not support geolocation, the promise is rejected with a clear error message:

"Geolocation is not supported by this browser."


πŸ” Permissions

Modern browsers require users to grant explicit permission to access location. Make sure you handle rejections gracefully in your app.


πŸ—‚οΈ File Structure

You can place the utility like this:

src/
└── utils/
    └── geolocation.ts

πŸ“ License

MIT β€” feel free to use, modify, and contribute!


🌍 Accurate user location with a simple Promise β€” great for maps, weather, or personalized experiences.

About

A lightweight TypeScript utility to fetch user's geolocation (latitude, longitude, accuracy) using the browser's native Geolocation API. Simple, Promise-based, and ideal for modern frontend apps.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published