countries-states-cities-neighborhood-database
v1.2.3
Published
contains country, state, cities, neighborhood, and building data
Readme
Countries-States-Cities-Neighborhood Database
A comprehensive library for working with country, state/region, city, and neighborhood data. This npm package provides simple, intuitive functions to query and filter location data from around the world.
Table of Contents
Installation
npm install countries-states-cities-neighborhood-databaseUsage
The package provides two ways to use the library:
1. API Factory (Recommended)
The API factory pattern is the simplest way to use the library, as it loads the dataset automatically:
const locationDB = require('countries-states-cities-neighborhood-database');
const api = locationDB.createAPI();
// Get all countries
const countries = api.getAllCountries();
// Get all cities in the United States
const usCities = api.getCitiesByCountry('US');
// Find cities near a location (within 50km)
const nearbyCities = api.getCitiesByGeoLocation(40.7128, -74.0060, 50);2. Direct Function Access
You can also use the functions directly with your own dataset:
const locationDB = require('countries-states-cities-neighborhood-database');
const data = require('./path/to/your/data.json');
// Get all countries
const countries = locationDB.getAllCountries(data);
// Get all cities in the United States
const usCities = locationDB.getCitiesByCountry(data, 'US');
// Find cities near a location (within 50km)
const nearbyCities = locationDB.getCitiesByGeoLocation(data, 40.7128, -74.0060, 50);Data Structure
This library expects your data to follow a specific structure:
[
{
"id": 231,
"name": "United States",
"iso2": "US",
"iso3": "USA",
"states": [
{
"id": 3901,
"name": "California",
"state_code": "CA",
"cities": [
{
"id": 52327,
"name": "San Francisco",
"latitude": "37.77493",
"longitude": "-122.41942"
}
]
}
]
}
]API Reference
The examples below show both usage patterns: the API factory method and direct function calls.
Countries
getAllCountries(data)
Returns an array of all countries in the dataset.
- Parameters:
data(Array): The complete dataset (not needed when using API factory)
- Returns: Array of country objects
- Example:
// Using API factory const countries = api.getAllCountries(); // Direct function call const countries = locationDB.getAllCountries(data); console.log(countries.length); // Number of countries
getCountryByCode(data, isoCode)
Finds a country by its ISO code (ISO2 or ISO3).
- Parameters:
data(Array): The complete dataset (not needed when using API factory)isoCode(String): ISO2 or ISO3 code to search for
- Returns: Country object or null if not found
- Example:
// Using API factory const usa = api.getCountryByCode('US'); const canada = api.getCountryByCode('CAN'); // Direct function call const usa = locationDB.getCountryByCode(data, 'US'); const canada = locationDB.getCountryByCode(data, 'CAN');
getCountryByName(data, name)
Finds a country by its name.
- Parameters:
data(Array): The complete datasetname(String): Country name to search for
- Returns: Country object or null if not found
- Example:
const japan = getCountryByName(data, 'Japan');
States/Regions
getAllStates(data)
Returns an array of all states/regions from all countries.
- Parameters:
data(Array): The complete dataset
- Returns: Array of state objects with country info attached
- Example:
const allStates = getAllStates(data); console.log(allStates[0]); // First state with country information
getStatesByCountry(data, countryIdentifier)
Returns all states for a specific country.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO code
- Returns: Array of state objects or empty array if country not found
- Example:
const usStates = getStatesByCountry(data, 'US'); const canadianProvinces = getStatesByCountry(data, 'Canada');
getStateByCode(data, countryIdentifier, stateCode)
Finds a specific state by its code.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO codestateCode(String): State code to search for
- Returns: State object or null if not found
- Example:
const california = getStateByCode(data, 'US', 'CA');
Cities
getAllCities(data)
Returns an array of all cities from all countries.
- Parameters:
data(Array): The complete dataset
- Returns: Array of city objects with country and state info attached
- Example:
const allCities = getAllCities(data); console.log(allCities.length); // Total number of cities
getCitiesByCountry(data, countryIdentifier)
Returns all cities for a specific country.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO code
- Returns: Array of city objects with state info attached
- Example:
const usCities = getCitiesByCountry(data, 'US');
getCitiesByState(data, countryIdentifier, stateIdentifier)
Returns all cities for a specific state/region.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO codestateIdentifier(String|Number): State ID, name, or code
- Returns: Array of city objects
- Example:
const texasCities = getCitiesByState(data, 'US', 'TX');
getCityByName(data, countryIdentifier, stateIdentifier, cityName)
Finds a specific city by name within a state.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO codestateIdentifier(String|Number): State ID, name, or codecityName(String): City name to search for
- Returns: City object or null if not found
- Example:
const boston = getCityByName(data, 'US', 'MA', 'Boston');
Neighborhoods
getNeighborhoodsByCity(data, countryIdentifier, stateIdentifier, cityIdentifier, basePath)
Returns all neighborhoods for a specific city.
- Parameters:
data(Array): The complete datasetcountryIdentifier(String|Number): Country ID, name, or ISO codestateIdentifier(String|Number): State ID, name, or codecityIdentifier(String|Number): City ID or namebasePath(String): Base path for neighborhood data files (default: '../data/json/neighborhoods')
- Returns: Array of neighborhood objects or empty array if city not found or has no neighborhoods
- Example:
const neighborhoods = getNeighborhoodsByCity(data, 'US', 'NY', 'New York');
Search & Geolocation
searchCities(data, query, countryIdentifier)
Searches for cities matching a query across all countries or a specific country.
- Parameters:
data(Array): The complete datasetquery(String): Search querycountryIdentifier(String|Number, optional): Country to limit search
- Returns: Array of matching city objects
- Example:
const springfields = searchCities(data, 'Springfield'); const canadianVancouvers = searchCities(data, 'Vancouver', 'CA');
getCitiesByGeoLocation(data, latitude, longitude, radiusKm)
Finds cities within a certain radius of GPS coordinates.
- Parameters:
data(Array): The complete datasetlatitude(Number): Latitude coordinatelongitude(Number): Longitude coordinateradiusKm(Number): Search radius in kilometers
- Returns: Array of city objects within the radius, sorted by distance
- Example:
// Cities within 50km of NYC const citiesNearNYC = getCitiesByGeoLocation(data, 40.7128, -74.0060, 50);
Internal Helper Functions
The library uses these internal helper functions:
calculateDistance(lat1, lon1, lat2, lon2): Calculates distance between two points using the Haversine formulatoRad(value): Converts degrees to radians
Project Structure
countries-states-cities-neighborhood-database/
│
├── data/
│ └── json/
│ ├── countries+states+cities.json # Main dataset
│ └── neighborhoods/ # Neighborhood data
│ └── [STATE_CODE]/
│ └── neighborhoods.json
│
├── src/
│ └── functions.js # Core functionality
│
├── index.js # API factory & exports
├── package.json
└── README.mdTesting
This package uses Jest for testing:
npm testTypeScript Usage
The package can be used in TypeScript applications. Here's a basic example with type definitions:
// Type definitions for the database
interface Country {
id: number;
name: string;
iso2: string;
iso3: string;
states: State[];
}
interface State {
id: number;
name: string;
state_code: string;
cities: City[];
}
interface City {
id: number;
name: string;
latitude: string;
longitude: string;
}
// Using the package with TypeScript
import { createAPI } from 'countries-states-cities-neighborhood-database';
const api = createAPI();
const countries: Country[] = api.getAllCountries();
const usStates: State[] = api.getStatesByCountry('US');See the full React component example in the examples directory.
License
ISC
