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 🙏

© 2026 – Pkg Stats / Ryan Hefner

pak-geodata

v0.12.2

Published

Comprehensive, typed, offline geographic data for all areas and cities in Pakistan

Readme

pak-geodata

NPM Version License: MIT

Comprehensive, typed, offline geographic data for all areas and cities in Pakistan.

Explore the Live Interactive Demo to test multi-script search, interactive map exploration, and reverse geocoding in real-time.

pak-geodata is an open-source, production-grade TypeScript and JavaScript client library providing offline access to verified geographic data for Pakistan.

It covers all 7 administrative provinces & territories, 136 verified cities & tehsils across Pakistan, and 3,953 foundational metropolitan and regional areas across 79 major & secondary cities.

Designed with zero runtime dependencies, strict geofencing, sub-millisecond lookups, and modular tree-shakeable subpath exports.


Features

  • Zero Runtime Dependencies: Completely self-contained with 0 runtime dependencies.
  • Dual Module Support: Full ESM (import) and CommonJS (require) support.
  • Bilingual Administrative Hierarchy (PakLocationItem): Unified administrative data structure connecting provinces, cities/districts, and areas with synchronized English and Urdu names.
  • Resilient O(1) Key Lookups: Pre-indexed instant resolution via getCityName(key, lang) and getAreaName(cityKey, areaKey, lang) supporting case-insensitive slugs, title names, and colloquial aliases.
  • Lightweight PWA Subpath (pak-geodata/hierarchy): Code-split micro-bundle (< 5 KB gzipped) designed specifically for offline-first Progressive Web Apps and reporting workflows.
  • Urdu Script & Numeral Normalization: Robust bidirectional matching across Eastern Arabic numerals (۳ vs 3), Urdu letter variants (ي vs ی, ك vs ک), and diacritic stripping.
  • Subpath Tree-Shaking: Import only the areas you need (e.g. pak-geodata/areas/lahore) to keep your bundle footprint under a few kilobytes.
  • Offline & Self-Contained: All verified golden datasets are bundled with the library: no remote API calls or latency.
  • Strict Geofencing & Validation: Every coordinate is rigorously validated within Pakistan territorial boundaries (23.5 <= lat <= 37.1, 60.8 <= lng <= 77.8) and city district bounding boxes.
  • Canonical Slugs: Standardized <city-slug>-<area-slug> identifiers across all datasets (e.g. lahore-dha-phase-5).
  • Multi-Script & Alias Search: Full support for English queries, colloquial aliases (e.g. "dha 5"), Urdu script queries (e.g. "گلبرگ"), and fuzzy typo tolerance.
  • Spatial Nearest Neighbor: Instant reverse geocoding via spherical Haversine distance calculations.
  • Postal Code Resolution: 5-digit Pakistan Post postal code lookup and reverse mapping.
  • Fully Typed: Written in TypeScript with complete type definitions (.d.ts).

Installation

npm install pak-geodata
yarn add pak-geodata
pnpm add pak-geodata

Quick Start

1. Provinces & Cities

import {
  getAllProvinces,
  getProvinceById,
  getAllCities,
  getCitiesByProvince,
  getCityById
} from 'pak-geodata';

// List all 7 provinces and federal territories
const provinces = getAllProvinces();
for (const p of provinces) {
  console.log(`${p.name} (${p.urduName}) - Capital: ${p.capitalCityId}`);
}

// Find a province by ID
const punjab = getProvinceById('punjab');
console.log(punjab?.name); // "Punjab"

// Retrieve all cities in a province
const punjabCities = getCitiesByProvince('punjab');
console.log(`Found ${punjabCities.length} cities in Punjab`);

// Get specific city details
const lahore = getCityById('lahore');
console.log(`${lahore?.name} coordinates:`, lahore?.coordinates);
console.log(`Verified areas count: ${lahore?.totalAreasCount}`);

2. Areas by City

import { getAreasByCity, getAllAreas } from 'pak-geodata';

// Retrieve all verified areas for a city
const lahoreAreas = getAreasByCity('lahore');
for (const area of lahoreAreas.slice(0, 5)) {
  console.log(`${area.name} [${area.id}] - Postal Code: ${area.postalCode}`);
}

// Total verified areas in Pakistan
const allAreas = getAllAreas();
console.log(`Total verified areas: ${allAreas.length}`); // 3953

3. Modular Subpath Imports (Tree-Shaking)

To minimize browser bundle size, import areas for specific cities directly without bundling the rest of the country:

// Only imports Lahore areas (~24 KB)
import { lahoreAreas } from 'pak-geodata/areas/lahore';

// Only imports Karachi areas (~26 KB)
import { karachiAreas } from 'pak-geodata/areas/karachi';

// Available subpaths:
// pak-geodata/hierarchy
// pak-geodata/institutions
// pak-geodata/areas/karachi
// pak-geodata/areas/lahore
// pak-geodata/areas/islamabad
// pak-geodata/areas/rawalpindi
// pak-geodata/areas/faisalabad
// pak-geodata/areas/gujranwala
// pak-geodata/areas/multan
// pak-geodata/areas/hyderabad
// pak-geodata/areas/peshawar
// pak-geodata/areas/quetta

3b. Educational Institutions Subpath (pak-geodata/institutions)

Import Pakistan's verified directory of 428 schools, colleges, and HEC-recognized universities (641 campuses/branches linked to verified cityId / provinceId) from a dedicated tree-shakeable subpath so geographic-only apps pay zero bundle cost:

import {
  getAllInstitutions,
  getInstitutionById,
  getInstitutionsByCategory,
  getInstitutionsByCity,
  getInstitutionsByProvince,
  getBranchesByInstitution,
  searchInstitutions
} from 'pak-geodata/institutions';

const universities = getInstitutionsByCategory('university'); // 284 universities
const tcsBranches = getBranchesByInstitution('the-city-school');
const matches = searchInstitutions('SMIU'); // Sindh Madressatul Islam University
const paf = searchInstitutions('PAF Chapter'); // The City School (PAF Campus, Karachi)

4. Intelligent Search

The search engine ranks results across multiple matching tiers:

  1. Exact match on name, ID, Urdu name, or alias
  2. Prefix match
  3. Substring / multi-word token match
  4. Fuzzy edit-distance fallback for typos
import { searchAreas } from 'pak-geodata';

// Search by colloquial alias scoped to a city
const results = searchAreas('dha 5', { cityId: 'lahore' });
console.log(results[0].id);   // "lahore-dha-phase-5"
console.log(results[0].name); // "DHA Phase 5"

// Search using Urdu script
const urduResults = searchAreas('کلفٹن');
for (const r of urduResults) {
  console.log(`${r.name} (${r.urduName}) in ${r.cityId}`);
}

// Scoped search with limit
const limited = searchAreas('phase', { cityId: 'islamabad', limit: 3 });

5. Reverse Geocoding & Spatial Nearest Neighbor

import { getNearestArea, haversineDistanceKm } from 'pak-geodata';

// Coordinates near Liberty Market, Gulberg, Lahore
const userLocation = { lat: 31.512, lng: 74.343 };

// Find closest verified area
const nearest = getNearestArea(userLocation);
console.log(`Nearest area: ${nearest?.name} (${nearest?.id})`);

// Find nearest area within a specific city and max radius (km)
const nearestInLahore = getNearestArea(userLocation, {
  cityId: 'lahore',
  maxDistanceKm: 5.0
});

// Calculate distance between two coordinate pairs
const lahoreCenter = { lat: 31.5204, lng: 74.3587 };
const karachiCenter = { lat: 24.8607, lng: 67.0011 };
const distance = haversineDistanceKm(lahoreCenter, karachiCenter);
console.log(`Distance: ${Math.round(distance)} km`); // ~1025 km

6. Postal Code Resolution

import { findAreaByPostalCode, findAreasByPostalCode } from 'pak-geodata';

// Resolve area by 5-digit Pakistan Post postal code (string or number)
const area = findAreaByPostalCode('54000');
console.log(`Postal code 54000: ${area?.name} (${area?.cityId})`);

// Find all areas sharing a postal code
const areas = findAreasByPostalCode(54000);

7. Bilingual Administrative Hierarchy & O(1) Lookups

import {
  getCityName,
  getAreaName,
  getProvincesAsLocationItems,
  getCitiesAsLocationItems,
  getAreasAsLocationItems,
  searchAreas
} from 'pak-geodata';

// 1. Instant O(1) bilingual name resolution
console.log(getCityName('Lahore', 'ur'));               // "لاہور"
console.log(getCityName('lahore', 'en'));               // "Lahore"
console.log(getAreaName('Lahore', 'Gulberg', 'ur'));    // "گلبرگ ۳"
console.log(getAreaName('lahore', 'lahore-gulberg-iii', 'en')); // "Gulberg III"

// 2. Bilingual hierarchy traversal
const provinces = getProvincesAsLocationItems();
console.log(provinces[0]); // { id: 'punjab', nameEn: 'Punjab', nameUr: 'پنجاب', type: 'province' }

const punjabCities = getCitiesAsLocationItems('punjab');
console.log(`Punjab has ${punjabCities.length} verified cities/districts`);

// 3. City-scoped bilingual search (returns PakLocationItem[])
const results = searchAreas('Lahore', 'DHA 5', 'ur');
console.log(results[0]);
// { id: 'lahore-dha-phase-5', nameEn: 'DHA Phase 5', nameUr: 'ڈی ایچ اے فیز ۵', type: 'area', parentId: 'lahore', ... }

Bilingual Hierarchy & Lightweight PWA Subpath

For applications requiring hierarchical administrative selection (Province → City/District → Area), pak-geodata provides a unified bilingual interface PakLocationItem and an ultra-lightweight < 5 KB gzipped subpath export:

import {
  getProvincesAsLocationItems,
  getCitiesAsLocationItems,
  getAreasAsLocationItems,
  getCityName,
  getAreaName,
  searchAreas
} from 'pak-geodata/hierarchy'; // Ultra-lightweight subpath (< 5 KB gzipped)

// 1. Traverse administrative hierarchy
const provinces = getProvincesAsLocationItems();
const sindhCities = getCitiesAsLocationItems('sindh');
const karachiAreas = getAreasAsLocationItems('karachi');

// 2. Resilient O(1) lookups (English & native Urdu Nastaliq)
console.log(getCityName('lahore', 'ur')); // "لاہور"
console.log(getAreaName('lahore', 'Gulberg', 'ur')); // "گلبرگ ۳"

// 3. City-scoped autocomplete search
const results = searchAreas('Lahore', 'گلبرگ ۳', 'ur');

📖 Full Implementation Recipe: For complete React form components, real-time localized display patterns, and offline database persistence, see the Bilingual Reporting & Tracking PWA Recipe.


Data Schema

PakLocationItem

type PakLocationType = 'province' | 'division' | 'district' | 'tehsil' | 'area';

interface PakLocationItem {
  id: string;                    // Canonical identifier (e.g. "lahore-gulberg-iii", "lahore", "punjab")
  nameEn: string;                // Standardized English name (e.g. "Gulberg III", "Lahore", "Punjab")
  nameUr: string;                // Native Urdu script (e.g. "گلبرگ ۳", "لاہور", "پنجاب")
  type: PakLocationType;         // Administrative level classification
  parentId?: string;             // Hierarchy linkage: area -> cityId -> provinceId
  coordinates?: {
    lat: number;                 // Latitude (WGS 84)
    lng: number;                 // Longitude (WGS 84)
  };
}

PakistanArea

interface PakistanArea {
  id: string;                    // Canonical: <city-slug>-<area-slug>
  cityId: string;                // e.g. "lahore", "karachi"
  provinceId: string;            // e.g. "punjab", "sindh"
  name: string;                  // Primary English name
  urduName?: string;             // Urdu Nastaliq / Naskh name
  aliases: string[];             // Common alternative names and abbreviations
  coordinates: {
    lat: number;                 // Latitude (WGS 84)
    lng: number;                 // Longitude (WGS 84)
  };
  bounds?: {
    minLat: number;
    maxLat: number;
    minLng: number;
    maxLng: number;
  };
  radiusKm?: number;             // Approximate radial span from centroid in km
  postalCode?: string;           // 5-digit Pakistan Post postal code
  type?: 'neighborhood' | 'sector' | 'commercial' | 'housing_scheme' | 'suburb' | 'industrial' | 'administrative';
  verified: boolean;             // True if verified via triangulation pipeline
  sources?: (string | ProvenanceSource)[]; // Structured or string provenance sources
}

PakistanCity

interface PakistanCity {
  id: string;                    // Canonical city slug (e.g. "lahore")
  name: string;                  // English name
  urduName: string;              // Urdu name
  provinceId: string;            // Province ID
  division?: string;             // Administrative division
  district?: string;             // District name
  coordinates: {
    lat: number;                 // City centroid latitude
    lng: number;                 // City centroid longitude
  };
  postalCodeRange?: [string, string]; // [minPostalCode, maxPostalCode]
  bounds?: {
    minLat: number;
    maxLat: number;
    minLng: number;
    maxLng: number;
  };
  totalAreasCount: number;       // Number of verified areas in dataset
}

PakistanProvince

interface PakistanProvince {
  id: string;                    // e.g. "punjab", "sindh", "islamabad-ict"
  name: string;                  // English name
  urduName: string;              // Urdu name
  capitalCityId: string;         // Capital city slug
  type: 'province' | 'federal_capital' | 'autonomous_territory';
}

Data Sources & Upstream Attribution

pak-geodata integrates cross-verified GIS records from:

  • National Geospatial-Intelligence Agency (NGA) & GeoNames: Populated places and urban quarters (PPLX) (CC-BY 4.0).
  • OpenStreetMap Contributors: Verified metropolitan neighborhood and arterial coordinates (ODbL 1.0).
  • UN OCHA / HDX COD: Administrative Common Operational Datasets for Pakistan boundaries (CC-BY-IGO).
  • Pakistan Post & PBS: Postal codes and administrative hierarchies.

See ATTRIBUTION.md for full attribution notices.


Licensing & Commercial Use FAQ

Commercial Use in Web & Mobile Apps

Under Section 4.3 of the Open Database License (ODbL), displaying Pakistani cities, autocomplete menus, checkout address pickers, or geocoding outputs within your application constitutes a "Produced Work". Using pak-geodata in your website or mobile app does NOT require you to open-source your proprietary code, backend services, or customer database. Simply include an attribution notice in your application's credits.


About The Mohsin Project

Free software for those who do good.

pak-geodata is an open-source public good engineered and maintained by The Mohsin Project.

The Mohsin Project exists because purpose-driven organizations and emergency teams lose momentum to outdated systems, expensive proprietary APIs, and scarce technical resources. We design, engineer, and deploy centralized digital solutions entirely free of cost so that nonprofits, humanitarian initiatives, and civic developers can focus on their mission.


License