npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

pincode-navigator

v1.0.1

Published

A lightweight package for calculating distances between Indian pincodes

Readme

Pincode Navigator

A lightweight NPM package for calculating distances between Indian pincodes and finding the closest pincode from a set of options. Uses Protocol Buffers for optimal performance and minimal package size.

Features

  • Calculate the distance between any two Indian pincodes
  • Find the closest pincode from a list of options
  • Calculate distances to multiple pincodes in bulk
  • Supports both embedded and custom pincode data
  • Protocol Buffers for 72% smaller data size and faster loading
  • Written in TypeScript with full type definitions
  • Minimal dependencies with small footprint (~6MB total)
  • Works in both Node.js and browser environments

Installation

npm install pincode-navigator
# or
yarn add pincode-navigator
# or
pnpm add pincode-navigator

Usage

Basic Usage

import { PincodeDistance } from 'pincode-navigator';

// Create a new instance with the default data
const pincodeDistance = new PincodeDistance();

// Wait for data to initialize (only needed once)
await pincodeDistance.waitForInitialization();
// Or use .then() syntax: pincodeDistance.waitForInitialization().then(() => {...})

// Calculate distance between two pincodes (returns distance in kilometers)
const distance = await pincodeDistance.calculateDistance('400001', '110001');
console.log(`Distance: ${distance.toFixed(2)} km`);

// Find the closest pincode from a list
const closestLocations = await pincodeDistance.findClosestPincode('400001', [
  '110001', // Delhi
  '600001', // Chennai
  '700001'  // Kolkata
]);

console.log('The closest location is:', closestLocations[0]);
// {
//   pincode: '700001',
//   latitude: 22.5726,
//   longitude: 88.3639,
//   officeName: 'Kolkata GPO',
//   district: 'Kolkata',
//   distance: 1681.74
// }

// Calculate distances to multiple pincodes in bulk (sorted by distance)
const distances = await pincodeDistance.calculateBulkDistances('400001', [
  '110001', // Delhi
  '600001', // Chennai
  '700001'  // Kolkata
]);
console.log('All distances:', distances);

Using Custom Data

You can provide your own Protocol Buffer file with pincode data:

import { PincodeDistance } from 'pincode-navigator';

// Initialize with a custom Protocol Buffer file
const pincodeDistance = new PincodeDistance({
  dataPath: '/path/to/custom/data.pbf'
});

// Alternatively, load custom data after initialization
await pincodeDistance.loadCustomData('/path/to/other/data.pbf');

Using Individual Functions

You can also use the individual utility functions directly:

import { haversine, loadProtobufData, findClosestLocations } from 'pincode-navigator';

// Calculate distance between two coordinates
const distance = haversine(18.9399, 72.8348, 28.6330, 77.2190);
console.log(`Distance: ${distance.toFixed(2)} km`);

// Load Protocol Buffer data manually (returns a Promise)
const locationMap = await loadProtobufData('/path/to/data.pbf');

// Find closest locations manually
const closestLocations = findClosestLocations(
  ['110001', '600001', '700001'],
  '400001',
  locationMap
);

Data Format & Structure

This package uses Protocol Buffers for efficient data storage and faster loading. The included data contains over 165,000 Indian pincodes with their geographical coordinates.

If you need to create your own Protocol Buffer data file, you can use the included schema (available in the GitHub repository) and the protobufjs library.

The Protocol Buffer format includes the following fields for each pincode:

  • pincode: The postal code (e.g., "400001")
  • officename: The name of the post office
  • latitude: Latitude in decimal degrees (e.g., 18.9399)
  • longitude: Longitude in decimal degrees (e.g., 72.8348)
  • district: District name
  • statename: State name

API Reference

PincodeDistance

Main class for pincode distance calculations.

Constructor

constructor(options?: PincodeDistanceOptions)
interface PincodeDistanceOptions {
  dataPath?: string;
  enableCache?: boolean;
}
  • options.dataPath: Optional path to a custom Protocol Buffer file containing pincode data
  • options.enableCache: Whether to enable distance caching for better performance (default: true)

Methods

async calculateDistance(fromPincode: string, toPincode: string): Promise<number>

Calculate distance between two pincodes.

  • fromPincode: Source pincode
  • toPincode: Destination pincode
  • Returns: Promise resolving to distance in kilometers
async findClosestPincode(toPincode: string, fromPincodes: string[]): Promise<LocationWithDistance[]>

Find the closest pincodes from a list to a target pincode.

  • toPincode: Destination pincode
  • fromPincodes: Array of source pincodes
  • Returns: Promise resolving to array of locations sorted by distance (closest first)
async calculateBulkDistances(fromPincode: string, toPincodes: string[]): Promise<LocationWithDistance[]>

Calculate distances from a source pincode to multiple destination pincodes.

  • fromPincode: Source pincode
  • toPincodes: Array of destination pincodes
  • Returns: Promise resolving to array of locations with distances
async loadCustomData(pbfPath: string): Promise<void>

Load a custom Protocol Buffer file with pincode data.

  • pbfPath: Path to the Protocol Buffer file
async waitForInitialization(): Promise<void>

Wait for data initialization to complete.

  • Returns: Promise that resolves when initialization is complete

Utility Functions

haversine(lat1: number, lon1: number, lat2: number, lon2: number): number

Calculate the distance between two points on earth using the Haversine formula.

  • Returns: Distance in kilometers

loadProtobufData(filePath: string): Promise<Map<string, LocationData>>

Load Protocol Buffer data and return a Promise resolving to a Map of location data indexed by pincode.

findClosestLocations(fromPincodes: string[], toPincode: string, locationMap: Map<string, LocationData>): LocationWithDistance[]

Find the closest locations from a list of pincodes to a target pincode.

Types

interface LocationData {
  officeName: string;
  latitude: number;
  longitude: number;
  district: string;
  statename: string;
}

interface LocationWithDistance extends LocationData {
  pincode: string;
  distance: number;
}

License

MIT