Package Exports
- pincode-navigator
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 officelatitude
: Latitude in decimal degrees (e.g., 18.9399)longitude
: Longitude in decimal degrees (e.g., 72.8348)district
: District namestatename
: 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 dataoptions.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 pincodetoPincode
: 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 pincodefromPincodes
: 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 pincodetoPincodes
: 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