quantaroute-geocoding
v1.1.0
Published
India-specific Node.js SDK for QuantaRoute Geocoding API with Location Lookup, Webhooks, and DigiPin processing
Maintainers
Readme
QuantaRoute Geocoding Node.js SDK
A unique Node.js/TypeScript library for geocoding addresses to DigiPin codes or reverse with groundbreaking Location Lookup API and offline processing capabilities. This library is designed for India 🇮🇳!
🚀 Unique Features
🔒 Enterprise-Grade Security - Runtime Protection & Code Security
- 🛡️ RASP Protection: Runtime Application Self-Protection with anti-debugging, integrity checks, and behavior monitoring
- 🔐 Secure API Key Storage: Encrypted storage with Symbol-based properties
- 🔏 Request Signing: HMAC-SHA256 signatures prevent tampering
- 🔒 Code Obfuscation: Production builds are automatically obfuscated
🎯 NEW: Location Lookup API - Service that even government doesn't provide!
- 🗺️ Administrative Boundary Lookup: Get state, division, locality, pincode, district, delivery status from coordinates
- 📍 19,000+ Pincode Boundaries (with 154,000 post offices): Complete coverage across India
- ⚡ Sub-100ms Response: Cached responses with database fallback
- 🎯 Government-Level Precision: Accuracy that official services don't offer
- 🔄 Batch Processing: Up to 100 locations per request
- 📊 Population Density Data: Mean, min, and max population density from Meta's 30-meter gridded data. [Deprecated]
🌟 Core Features
- 🌐 Online API Integration: Full access to QuantaRoute Geocoding API
- 🔌 Offline Processing: Process coordinates ↔ DigiPin without internet
- 📊 TypeScript Support: Full type definitions included
- 🚀 Modern Async/Await: Promise-based API
- 📈 Error Handling: Comprehensive error types and handling
- 🔄 Retry Logic: Automatic retry with exponential backoff
- 🎯 Rate Limit Handling: Intelligent rate limit management
Installation
npm install quantaroute-geocodingFor offline DigiPin processing, also install the DigiPin library:
npm install digipinQuick Start
🚀 NEW: Unique Location Lookup API
import { QuantaRouteClient } from 'quantaroute-geocoding';
// Initialize client
const client = new QuantaRouteClient({
apiKey: 'your-api-key'
});
// 🚀 Unique: Get administrative boundaries from coordinates
const result = await client.lookupLocationFromCoordinates(28.6139, 77.2090);
console.log(`Pincode: ${result.administrative_info.pincode}`); // 110001
console.log(`State: ${result.administrative_info.state}`); // Delhi
console.log(`Division: ${result.administrative_info.division}`); // New Delhi Central
console.log(`Locality: ${result.administrative_info.locality}`); // Nirman Bhawan SO
console.log(`District: ${result.administrative_info.district}`); // New Delhi
console.log(`Delivery: ${result.administrative_info.delivery}`); // Delivery
console.log(`DigiPin: ${result.digipin}`); // 39J-438-TJC7
console.log(`Response Time: ${result.response_time_ms}ms`); // <100ms
// 🚀 Unique: Get boundaries from DigiPin
const digipinResult = await client.lookupLocationFromDigiPin("39J-438-TJC7");
console.log(`Pincode: ${digipinResult.administrative_info.pincode}`);
console.log(`State: ${digipinResult.administrative_info.state}`);
console.log(`Division: ${digipinResult.administrative_info.division}`);
console.log(`Locality: ${digipinResult.administrative_info.locality}`);
console.log(`District: ${digipinResult.administrative_info.district}`);
// 📊 Get live statistics (19,000+ boundaries with 154,000 post offices)
const stats = await client.getLocationStatistics();
console.log(`Total Boundaries: ${stats.totalBoundaries.toLocaleString()}`);
console.log(`Total States: ${stats.totalStates}`);🌟 Traditional Geocoding API
// Geocode an address
const geocodeResult = await client.geocode("India Gate, New Delhi, India");
console.log(`DigiPin: ${geocodeResult.digipin}`);
console.log(`Coordinates: ${geocodeResult.coordinates}`);
// Convert coordinates to DigiPin
const coordResult = await client.coordinatesToDigiPin(28.6139, 77.2090);
console.log(`DigiPin: ${coordResult.digipin}`);
// Reverse geocode DigiPin - Get Nominatim/OpenStreetMap address with DigiPin (Our USP!)
const reverseResult = await client.reverseGeocode("39J-438-TJC7");
console.log(`DigiPin: ${reverseResult.digipin}`); // Always returned - Our USP!
console.log(`Coordinates: ${reverseResult.coordinates}`);
console.log(`Address: ${reverseResult.address}`);
console.log(`Display Name: ${reverseResult.displayName}`);
console.log(`Street: ${reverseResult.addressComponents.road}`);
console.log(`House Name: ${reverseResult.addressComponents.amenity || reverseResult.addressComponents.name}`);Offline Processing
import { OfflineProcessor } from 'quantaroute-geocoding';
// Initialize offline processor
const processor = new OfflineProcessor();
// Convert coordinates to DigiPin (offline)
const offlineResult = processor.coordinatesToDigiPin(28.6139, 77.2090);
console.log(`DigiPin: ${offlineResult.digipin}`);
// Convert DigiPin to coordinates (offline)
const coordsResult = processor.digiPinToCoordinates("39J-438-TJC7");
console.log(`Coordinates: ${coordsResult.coordinates}`);
// Validate DigiPin format
const validation = processor.validateDigiPin("39J-438-TJC7");
console.log(`Valid: ${validation.isValid}`);
// Calculate distance between coordinates
const distance = processor.calculateDistance(28.6139, 77.2090, 28.6150, 77.2100);
console.log(`Distance: ${distance.toFixed(2)} km`);🔔 Webhook Management
// Register a webhook endpoint
const webhook = await client.registerWebhook({
url: 'https://your-app.com/webhooks',
events: [
'location.lookup.completed',
'geocoding.completed',
'rate_limit.exceeded'
],
secret: 'your-webhook-secret' // Optional: for signature verification
});
console.log(`Webhook registered: ${webhook.id}`);
// List all webhooks
const webhooks = await client.listWebhooks();
webhooks.forEach(wh => {
console.log(`${wh.id}: ${wh.url} (${wh.events.length} events)`);
});
// Get a specific webhook
const webhookDetails = await client.getWebhook(webhook.id);
console.log(`Active: ${webhookDetails.isActive}`);
console.log(`Failures: ${webhookDetails.failureCount}`);
// Test webhook delivery
const testResult = await client.testWebhook(webhook.id);
console.log(`Test delivered: ${testResult.delivered}`);
// Delete webhook
await client.deleteWebhook(webhook.id);Supported Webhook Events
location.lookup.completed- Location lookup completed successfullylocation.lookup.failed- Location lookup failedlocation.batch_lookup.completed- Batch location lookup completedlocation.batch_lookup.failed- Batch location lookup failedgeocoding.completed- Geocoding completed successfullygeocoding.failed- Geocoding failedbulk_processing.started- Bulk processing startedbulk_processing.completed- Bulk processing completedbulk_processing.failed- Bulk processing failedrate_limit.exceeded- Rate limit exceededapi_key.usage_warning- API key usage warning (80% threshold)webhook.test- Test webhook event
Webhook Security
Webhooks include HMAC-SHA256 signatures for verification:
import crypto from 'crypto';
// Verify webhook signature
function verifyWebhookSignature(
body: string,
signature: string,
secret: string
): boolean {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(body)
.digest('hex');
const receivedSignature = signature.replace('sha256=', '');
return expectedSignature === receivedSignature;
}Webhook Payload Format
{
event: 'location.lookup.completed',
timestamp: '2025-11-10T12:00:00.000Z',
data: {
coordinates: { latitude: 28.6139, longitude: 77.2090 },
digipin: '39J-438-TJC7',
administrative_info: {
country: 'India',
state: 'Delhi',
division: 'New Delhi Central',
locality: 'Nirman Bhawan SO',
pincode: '110001'
}
}
}🚀 Unique Location Lookup API
Dedicated Location Lookup Client
import { LocationLookupClient } from 'quantaroute-geocoding';
// Initialize dedicated location client
const locationClient = new LocationLookupClient({
apiKey: 'your-api-key'
});
// Single coordinate lookup
const result = await locationClient.lookupCoordinates(28.6139, 77.2090);
console.log(`📮 Pincode: ${result.administrative_info.pincode}`);
console.log(`🏢 Office: ${result.administrative_info.locality}`);
console.log(`🏛️ Division: ${result.administrative_info.division}`);
console.log(`⚡ Response Time: ${result.response_time_ms}ms`);
// DigiPin to boundaries
const digipinResult = await locationClient.lookupDigiPin("39J-438-TJC7");
console.log(`Administrative boundaries:`, digipinResult.administrative_info);
// Batch processing (up to 100 locations)
const locations = [
{ latitude: 28.6139, longitude: 77.2090 },
{ latitude: 19.0760, longitude: 72.8777 },
{ digipin: "39J-438-TJC7" }
];
const batchResults = await locationClient.batchLookup(locations);
console.log(`Processed ${batchResults.results.length} locations`);
// Live statistics
const stats = await locationClient.getStatistics();
console.log(`🗺️ Total Boundaries: ${stats.totalBoundaries.toLocaleString()}`);
console.log(`⚡ Cache Size: ${stats.cacheSize}`);
// Coverage information
const coverage = await locationClient.getCoverageInfo();
console.log(`Service capabilities:`, coverage);Location Lookup Output Format
interface LocationLookupResult {
administrative_info: {
pincode: string; // "110001"
locality: string; // "Nirman Bhawan SO"
division: string; // "New Delhi Central"
state: string; // "Delhi"
country: string; // "India"
delivery?: string; // "Delivery"
district?: string; // "New Delhi"
};
coordinates: {
latitude: number; // 28.6139
longitude: number; // 77.2090
};
digipin: string; // "39J-438-TJC7"
confidence: number; // 0.95
source: 'cache' | 'database';
response_time_ms?: number; // 45
}Why This is Unique?
🎯 Government-Level Precision: Access to administrative boundaries that even government APIs don't provide at this level of detail and accessibility.
📍 19,000+ Boundaries (with 154,000 post offices): Complete coverage of Indian postal boundaries with sub-district level precision.
⚡ Performance: Sub-100ms cached responses, <500ms database queries.
🔄 Batch Processing: Process up to 100 locations in a single API call.
✨ Unique Value: The only service providing this level of administrative boundary lookup precision for India.
Configuration
Environment Variables
Set your API key as an environment variable:
export QUANTAROUTE_API_KEY="your-api-key"Client Configuration
const client = new QuantaRouteClient({
apiKey: 'your-key',
baseURL: 'https://api.quantaroute.com', // Custom base URL
timeout: 30000, // Request timeout in milliseconds
maxRetries: 3 // Maximum retry attempts
});Error Handling
import {
QuantaRouteError,
APIRequestError,
RateLimitError,
AuthenticationError,
ValidationError
} from 'quantaroute-geocoding';
try {
const result = await client.geocode("Invalid address");
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limit exceeded. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof AuthenticationError) {
console.log("Invalid API key");
} else if (error instanceof ValidationError) {
console.log(`Validation error: ${error.message}`);
} else if (error instanceof APIRequestError) {
console.log(`API error: ${error.message} (Status: ${error.statusCode})`);
}
}Browser Usage & CORS
Frontend Applications
This package works in both Node.js and browser environments. For browser usage:
// Works in React, Vue, Angular, vanilla JS, etc.
import { QuantaRouteClient } from 'quantaroute-geocoding';
const client = new QuantaRouteClient({
apiKey: 'your-api-key'
});
// Use in your frontend application
const handleGeocode = async () => {
try {
const result = await client.lookupLocationFromCoordinates(28.6139, 77.2090);
console.log('Location data:', result);
} catch (error) {
console.error('Geocoding error:', error);
}
};CORS Configuration
The QuantaRoute API server is configured to allow cross-origin requests. If you encounter CORS issues:
- Check your API key: Ensure you're using a valid API key
- Verify the endpoint: Make sure you're calling the correct API endpoints
- Browser dev tools: Check the Network tab for detailed error information
Note: CORS issues are server-side configuration problems, not client-side package issues.
TypeScript Support
This package includes full TypeScript definitions:
import {
QuantaRouteClient,
LocationLookupResult,
GeocodeResult,
LocationStatistics,
BatchLocationRequest
} from 'quantaroute-geocoding';
// All types are fully typed
const client: QuantaRouteClient = new QuantaRouteClient({ apiKey: 'key' });
const result: LocationLookupResult = await client.lookupLocationFromCoordinates(28.6139, 77.2090);API Limits
Traditional Geocoding API
| Tier | Requests/Minute | Monthly Limit | Batch Size | |------|----------------|---------------|------------| | Free | 10 | 1,000 | 50 | | Paid | 100 | 10,000 | 100 | | Enterprise | 1,000 | Unlimited | 100 |
🚀 Unique Location Lookup API
| Tier | Requests/Minute | Monthly Limit | Batch Size | Boundaries | |------|----------------|---------------|------------|------------| | Free | 20 | 25,000 | 50 | 19,000+ (with 154,000 post offices) | | Paid | 200 | 50,000 | 100 | 19,000+ (with 154,000 post offices) | | Enterprise | 10,000,000 | Unlimited | 100 | 19,000+ (with 154,000 post offices) |
Performance Guarantees:
- ⚡ Cached responses: <100ms
- 🔍 Database queries: <500ms
- 📊 Batch processing: <50ms per location
- 🎯 99.9% uptime SLA (Enterprise)
Examples
Check out the examples/ directory for more comprehensive examples:
basic-usage.js- Basic geocoding operationslocation-lookup.js- Unique Location Lookup APIwebhooks.js- Webhook management and event handlingoffline-processing.js- Offline DigiPin operations
Support
- 📧 Email: [email protected]
- 🌐 Website: https://quantaroute.com
- 📖 Traditional API Docs: https://api.quantaroute.com/v1/digipin/docs
- 🚀 NEW: Location Lookup API: https://api.quantaroute.com/v1/location
- 🔔 Webhook API: https://api.quantaroute.com/v1/digipin/webhooks
- 📊 Live Statistics: https://api.quantaroute.com/v1/location/stats
🚀 What Makes This Unique?
QuantaRoute's Location Lookup API is the first and only service to provide:
✨ Government-Level Precision: Administrative boundary data that even government APIs don't provide at this level of detail and accessibility.
📍 Complete Coverage: 19,000+ postal boundaries (with 154,000 post offices) across India with sub-district precision.
⚡ Blazing Performance: Sub-100ms cached responses, guaranteed <500ms database queries.
🎯 Unique Value Proposition: The only service providing this level of administrative boundary lookup precision for India.
🔄 Developer-Friendly: Simple APIs, comprehensive TypeScript support, and excellent documentation.
Ready to revolutionize your location intelligence applications?
Changelog
[1.1.0] - 2025-11-25
🔒 Security Enhancements (Major Update)
- 🛡️ RASP Protection: Runtime Application Self-Protection with anti-debugging, integrity checks, and behavior monitoring
- 🔐 Secure API Key Storage: Encrypted storage with Symbol-based properties
- 🔏 Request Signing: HMAC-SHA256 signatures prevent tampering
- 🔒 Code Obfuscation: Production builds automatically obfuscated
- 🚫 Source Map Removal: Prevents reverse engineering
[1.0.4] - 2025-11-23
Added
- Enhanced reverse geocoding with detailed address components
address,displayName, andaddressComponentsfields
[1.0.3] - 2025-11-10
Added
- 🔔 Webhook Management: Register, list, delete, and test webhook endpoints
- 🔔 Webhook Events: Support for 12 webhook event types
- 🔔 Webhook Security: HMAC-SHA256 signature verification
- 🔔 Webhook Examples: Comprehensive webhook usage examples
Enhanced
- Improved error handling for webhook operations
- Added webhook event types and interfaces
[1.0.2] - 2025-11-01
Added
- 🎉 Population Density Data: Added mean, min, and max population density fields from Meta's 30-meter gridded data [Deprecated]
- 📍 District Information: Added district field for Indian district division as per official records
- ✅ Delivery Status: Added delivery field for pincode delivery status
- 🌍 Complete Geographic Data: Added state and country fields for comprehensive location information
Enhanced
- Improved administrative boundary data with complete coverage (19,000+ postal boundaries with 154,000 post offices)
[1.0.1] - Previous Release
- Initial stable release with Location Lookup API
[1.0.0] - Initial Release
- Traditional geocoding API with DigiPin support
- Offline processing capabilities
License
MIT License - see LICENSE file for details.
