### Download pages with 'examples' in URL using wget Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/src/configs/discovery/notes.md Uses `wget` to recursively download all HTML pages from a starting URL that contain 'examples' in their URL. The output is saved to a single file. ```bash wget -r --accept-regex=.*examples.* -O wget-examples.txt https://api.census.gov/data.html ``` -------------------------------- ### Start Node REPL with Shadow-cljs Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md Launch a Node.js REPL environment for shadow-cljs development. ```clojure (shadow.cljs.devtools.api/node-repl) ``` -------------------------------- ### Install CitySDK with npm Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md Use npm to install the CitySDK package. ```bash npm install citysdk ``` -------------------------------- ### Start Remote REPL with shadow-cljs Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md Initiate a remote REPL session using shadow-cljs. ```bash shadow-cljs clj-repl ``` -------------------------------- ### CommonJS Installation Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/assets/highlight/README.md Install highlight.js using npm for use in CommonJS environments. ```bash npm install highlight.js --save ``` -------------------------------- ### Basic Highlight.js Initialization Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/assets/highlight/README.md Include these files and call initHighlightingOnLoad for basic setup. This automatically detects and highlights code within
 tags.

```html



```

--------------------------------

### Installation

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md

Install CitySDK using npm.

```APIDOC
## Installation

```
npm install citysdk
```
```

--------------------------------

### Start REPL Server with shadow-cljs

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/README.md

Initiates a shadow-cljs REPL server for development. This command is typically run in a terminal.

```bash
shadow-cljs node-repl
```

--------------------------------

### Start Project REPL and Connect with Calva

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md

Initiate a ClojureScript REPL connection in VSCode using the Calva extension.

```bash
Calva: Start a Project REPL and Connect (aka jack-in)
```

--------------------------------

### Watch Shadow-cljs Build

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md

Start watching a specific build configuration in shadow-cljs from the REPL.

```clojure
(shadow/watch :)
```

--------------------------------

### Get Census Statistics Values by ID with API Key

Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md

This example is similar to fetching values by ID but includes an API key, which is required for making more than 500 calls per day. Ensure you replace '' with your actual key.

```javascript
census(
    {
        vintage: 2015, // required
        geoHierarchy: {
            // required
            county: {
                lat: 28.2639,
                lng: -80.7214,
            },
        },
        sourcePath: ['cbp'], // required
        values: ['ESTAB'], // required
        statsKey: '', // required for > 500 calls per day
    },
    (err, res) => console.log(res)
)

// result -> [{"ESTAB":13648,"state":"12","county":"009"}]
```

--------------------------------

### Fetch CBP Data with String Vintage

Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md

Example demonstrating the use of a string value for the 'vintage' parameter when fetching County Business Patterns (CBP) data.

```javascript
{
  "vintage": "2015",
  "geoHierarchy": { "county": { "lat": 28.2639, "lng": -80.7214 } },
  "sourcePath": [ "cbp" ],
  "values": [ "ESTAB" ]
}
```

--------------------------------

### Accessing Statistical Data with Predicates

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md

This example demonstrates how to query for statistical data using predicates to filter results based on specific criteria, such as a population range.

```APIDOC
## census

### Description
Retrieves statistical data from the US Census Bureau.

### Method
`census(options, callback)`

### Parameters
#### Options Object
- **vintage** (string) - Required - The vintage year of the data (e.g., '2017').
- **geoHierarchy** (object) - Required - Specifies the geographic hierarchy (e.g., state, county).
  - **state** (string) - Required - State FIPS code.
  - **county** (string) - Required - County FIPS code or '*'.
- **sourcePath** (array) - Required - Path to the data source (e.g., ['acs', 'acs1']).
- **values** (array) - Required - List of statistical values to retrieve (e.g., ['NAME']).
- **predicates** (object) - Optional - Filters for statistical values.
  - **B01001_001E** (string) - Example predicate for population range (e.g., '0:100000').
- **statsKey** (string) - Required - Your API key.

### Callback Function
- **err** - Error object if an error occurred.
- **res** - Response object containing the data.

### Request Example
```javascript
census(
    {
        vintage: '2017',
        geoHierarchy: {
            state: '51',
            county: '*',
        },
        sourcePath: ['acs', 'acs1'],
        values: ['NAME'],
        predicates: {
            B01001_001E: '0:100000',
        },
        statsKey: '',
    },
    (err, res) => console.log(res)
)
```

### Response Example
```json
[
  {
    "NAME":"Augusta County, Virginia",
    "B01001_001E" : 75144,
    "state":"51",
    "county":"015"
  },
  {
    "NAME":"Bedford County, Virginia",
    "B01001_001E" : 77974,
    "state":"51",
    "county":"019"
  },
  ...
]
```
```

--------------------------------

### Retrieving Cartographic GeoJSON

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md

This example demonstrates how to fetch Cartographic Boundary files translated into GeoJSON format, with options for geographic resolution.

```APIDOC
## census (Cartographic GeoJSON)

### Description
Retrieves Cartographic Boundary files in GeoJSON format.

### Method
`census(options, callback)`

### Parameters
#### Options Object
- **vintage** (number) - Required - The vintage year of the data (e.g., 2017).
- **geoHierarchy** (object) - Required - Specifies the geographic hierarchy.
  - **'metropolitan statistical area/micropolitan statistical area'** (string) - Required - Set to '*' to retrieve all MSAs/MSAs.
- **geoResolution** (string) - Required - The desired geographic resolution. Options: '500k', '5m', '20m'.

### Callback Function
- **err** - Error object if an error occurred.
- **res** - Response object containing the GeoJSON data.

### Request Example (Node.js with fs module)
```javascript
import fs from 'fs'

census(
    {
        vintage: 2017,
        geoHierarchy: {
            'metropolitan statistical area/micropolitan statistical area': '*',
        },
        geoResolution: '500k', // required
    },
    (err, res) => {
        fs.writeFile('./directory/filename.json', JSON.stringify(res), () => console.log('done'))
    }
)
```

### Notable Example (State and County GeoJSON)
```javascript
census(
    {
        vintage: '2017',
        geoHierarchy: {
            state: '51',
            county: '*',
        },
        geoResolution: '500k', // required
    },
    (err, res) => console.log(res)
)
```

### Response Example (GeoJSON FeatureCollection)
```json
{
  "type": "FeatureCollection",
  "features": [
    // GeoJSON features representing geographic boundaries
  ]
}
```
```

--------------------------------

### ESM Import

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md

Starting with v2.3.0, CitySDK ships as an ESM export. This shows the migration from older versions.

```APIDOC
## V 2.3 Changes

Starting with v2.3.0, CitySDK ships as an ESM export

Migration:

```js
// 2.2.x or below
const census = require('citysdk')
// 2.3.x or above
import census from 'citysdk'
```
```

--------------------------------

### Fetch Statistics Data

Source: https://context7.com/uscensusbureau/citysdk/llms.txt

This example demonstrates how to fetch statistical data, such as establishment counts or population, for specified geographic areas using the CitySDK. It shows how to specify vintage, geographic hierarchy, data sources, and desired variables. Predicates can be used to filter results based on specific criteria.

```APIDOC
## Fetch Statistics Data

### Description
This operation fetches statistical data from the Census Bureau API. You can specify the vintage year, geographic hierarchy (e.g., county, state), data source paths (e.g., 'cbp' for County Business Patterns, 'acs' for American Community Survey), and the specific values (variables) you are interested in. An API key is required.

### Method
`census(options, callback)`

### Parameters
- `options` (object) - Configuration object for the data request:
  - `vintage` (number|string) - The data vintage year (e.g., 2015) or 'timeseries'.
  - `geoHierarchy` (object) - Defines the geographic scope of the request. Can include properties like `county`, `state`, `us`, etc., with specific IDs or '*' for all.
  - `sourcePath` (array) - An array of strings specifying the data product path (e.g., `['cbp']`).
  - `values` (array) - An array of strings specifying the variable IDs to retrieve (e.g., `['ESTAB']`).
  - `statsKey` (string) - Your Census Bureau API key.
  - `predicates` (object, optional) - Key-value pairs for filtering results (e.g., `{ B01001_001E: '0:100000' }` for population range).
- `callback` (function) - A function to handle the response. It receives `err` and `res` arguments.

### Request Example
```js
import census from 'citysdk'

census(
  {
    vintage: 2015,
    geoHierarchy: { county: { lat: 28.2639, lng: -80.7214 } },
    sourcePath: ['cbp'],
    values: ['ESTAB'],
    statsKey: '',
  },
  (err, res) => {
    if (err) return console.error(err)
    console.log(res)
  }
)
```

### Response
#### Success Response
- `res` (array) - An array of JSON objects, where each object contains the requested data for a specific geographic entity. Census error codes are returned as prefixed strings (e.g., "NAN: -999999999").

#### Response Example
```json
[
  { "ESTAB": 13648, "state": "12", "county": "009" } 
]
```
```

```APIDOC
## Fetch Statistics Data with Predicates

### Description
This example shows how to filter statistical data using predicates. Here, it retrieves county data for Virginia and filters for counties with a population between 0 and 100,000.

### Method
`census(options, callback)`

### Parameters
- `options` (object) - Configuration object:
  - `vintage` (string) - The data vintage year (e.g., '2017').
  - `geoHierarchy` (object) - Geographic scope (e.g., `{ state: '51', county: '*' }`).
  - `sourcePath` (array) - Data source path (e.g., `['acs', 'acs1']`).
  - `values` (array) - Variable IDs (e.g., `['NAME']`).
  - `statsKey` (string) - Your Census Bureau API key.
  - `predicates` (object) - Filtering criteria. For example, `B01001_001E: '0:100000'` filters for population between 0 and 100,000.
- `callback` (function) - Callback function for the response.

### Request Example
```js
import census from 'citysdk'

census(
  {
    vintage: '2017',
    geoHierarchy: { state: '51', county: '*' },
    sourcePath: ['acs', 'acs1'],
    values: ['NAME'],
    predicates: {
      B01001_001E: '0:100000',
    },
    statsKey: '',
  },
  (err, res) => {
    if (err) return console.error(err)
    console.log(res)
  }
)
```

### Response
#### Success Response
- `res` (array) - An array of JSON objects matching the predicate filters.

#### Response Example
```json
[
  { "NAME": "Augusta County, Virginia", "B01001_001E": 75144, "state": "51", "county": "015" },
  { "NAME": "Bedford County, Virginia",  "B01001_001E": 77974, "state": "51", "county": "019" }
]
```
```

```APIDOC
## Fetch Timeseries Data

### Description
This operation retrieves timeseries data for specified geographic areas and variables. It allows you to specify a 'timeseries' vintage and filter data by time, industry codes (NAICS), and other relevant predicates.

### Method
`census(options, callback)`

### Parameters
- `options` (object) - Configuration object:
  - `vintage` (string) - Set to `'timeseries'` to fetch timeseries data.
  - `geoHierarchy` (object) - Geographic scope (e.g., `{ us: '*' }`).
  - `sourcePath` (array) - Data source path (e.g., `['asm', 'industry']`).
  - `values` (array) - Variable IDs to retrieve (e.g., `['EMP', 'NAICS_TTL', 'GEO_TTL']`).
  - `predicates` (object) - Filtering criteria, such as `time` and `NAICS` codes.
  - `statsKey` (string) - Your Census Bureau API key.
- `callback` (function) - Callback function for the response.

### Request Example
```js
import census from 'citysdk'

census(
  {
    vintage: 'timeseries',
    geoHierarchy: { us: '*' },
    sourcePath: ['asm', 'industry'],
    values: ['EMP', 'NAICS_TTL', 'GEO_TTL'],
    predicates: { time: '2016', NAICS: '31-33' },
  },
  (err, res) => {
    if (err) return console.error(err)
    console.log(res)
  }
)
```

### Response
#### Success Response
- `res` (array) - An array of JSON objects containing timeseries data matching the specified criteria.

#### Response Example
```json
[
  {
    "EMP": 11112764,
    "NAICS_TTL": "Manufacturing",
    "GEO_TTL": "United States",
    "time": "2016",
    "NAICS": "31-33",
    "us": "1"
  }
]
```
```

--------------------------------

### Accessing Timeseries Statistical Data

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md

This example shows how to retrieve timeseries statistical data, which is useful for analyzing trends over time. Note that mapping timeseries data is unsupported.

```APIDOC
## census (Timeseries Data)

### Description
Retrieves timeseries statistical data. Useful for trend analysis.

### Method
`census(options, callback)`

### Parameters
#### Options Object
- **vintage** (string) - Required - Must be set to 'timeseries'.
- **geoHierarchy** (object) - Required - Specifies the geographic hierarchy.
  - **us** (string) - Required - Set to '*' for United States level data.
- **sourcePath** (array) - Required - Path to the data source (e.g., ['asm', 'industry']).
- **values** (array) - Required - List of statistical values to retrieve (e.g., ['EMP', 'NAICS_TTL', 'GEO_TTL']).
- **predicates** (object) - Optional - Filters for statistical values.
  - **time** (string) - Required for timeseries - The year for the timeseries data (e.g., '2016').
  - **NAICS** (string) - Optional - NAICS code for filtering (e.g., '31-33').

### Callback Function
- **err** - Error object if an error occurred.
- **res** - Response object containing the data.

### Request Example
```javascript
census(
    {
        vintage: 'timeseries',
        geoHierarchy: {
            us: '*',
        },
        sourcePath: ['asm', 'industry'],
        values: ['EMP', 'NAICS_TTL', 'GEO_TTL'],
        predicates: { time: '2016', NAICS: '31-33' },
    },
    (err, res) => console.log(res)
)
```

### Response Example
```json
[{"EMP": 11112764, 
  "NAICS_TTL": "Manufacturing", 
  "GEO_TTL": "United States", 
  "time": "2016", 
  "NAICS": "31-33", 
  "us":"1"}]
```
```

--------------------------------

### Discover Census API Identifiers

Source: https://context7.com/uscensusbureau/citysdk/llms.txt

Provides examples of `sourcePath` and `values` identifiers for the Census API. Use the Census Developers' Microsite or Census Discovery Tool to find more.

```javascript
// Census API example URL:
// https://api.census.gov/data/2017/acs/acs1?get=NAME,group(B01001)&for=us:1
//                                    └─┬─┘└───┬────┘
//                                  vintage  sourcePath → ['acs', 'acs1']

// Resources for discovering datasets and variable IDs:
// 1. Census Developers' Microsite: https://www.census.gov/developers/
// 2. Census Discovery Tool:        https://api.census.gov/data.html
// 3. Request an API key:           https://api.census.gov/data/key_signup.html

// Common sourcePath examples:
const DATASETS = {
  'ACS 5-year':             ['acs', 'acs5'],
  'ACS 1-year':             ['acs', 'acs1'],
  'County Business Patterns':['cbp'],
  'Annual Survey of Manufactures': ['asm', 'industry'],
  'Decennial Census SF1':   ['dec', 'sf1'],
}

// Common values (ACS variable IDs):
const VARIABLES = {
  'Total Population':       'B01001_001E',
  'GINI Inequality Index':  'B19083_001E',
  'Median Household Income':'B19013_001E',
  'Total Housing Units':    'B25001_001E',
  'Travel Time to Work':    'B08303_001E',
  'Unweighted Sample Count':'B00001_001E',
}
```

--------------------------------

### Request a single geographic area by coordinate

Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md

This example demonstrates how to request data for a specific geographic area by providing latitude and longitude coordinates. The library automatically handles the creation of the full geographic hierarchy (GEOID).

```APIDOC
## Request a single geographic area by coordinate

### Description
Requests data for a specific geographic area using latitude and longitude. The library constructs the full GEOID by inferring necessary parent geographies.

### Method
`census()`

### Parameters
#### Options Object
- **vintage** (integer) - Required - The vintage year for the geographic data.
- **geoHierarchy** (object) - Required - Defines the geographic area to query.
  - **county** (object) - Required - An object containing `lat` and `lng` for the coordinate.
    - **lat** (float) - Required - The latitude coordinate.
    - **lng** (float) - Required - The longitude coordinate.

### Request Example
```javascript
import census from 'citysdk'

census(
    {
        vintage: 2015, // required
        geoHierarchy: {
            // required
            county: {
                lat: 28.2639,
                lng: -80.7214,
            },
        },
    },
    (err, res) => console.log(res)
)
```

### Response
#### Success Response (200)
Returns a JSON object containing the requested geographic data, potentially including inferred parent geographies.

#### Response Example
```json
{
  "vintage": "2015",
  "geoHierarchy": {
    "state": "12",
    "county": "009"
  }
}
```
```

--------------------------------

### Merge Census Stats into GeoJSON Properties with CitySDK

Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/index.html

This example shows how to fetch census data and merge it directly into the 'properties' of GeoJSON features. It's useful for visualizing census data on maps. Note the use of latitude and longitude for geocoding.

```javascript
let census = require('citysdk')
census(
  {
    "vintage": 2016,
    "geoHierarchy": {
      "county": { lat: 28.2639, lng: -80.7214 },
      "tract": "*"
    },
    "sourcePath": ["acs", "acs5"],
    "values": ["B00001_001E"],
    "geoResolution": "500k"
  },
  (err, res) => console.log(res)
)
 TRY IT
```

--------------------------------

### Initialize Git Repository

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md

Initialize a new Git repository for version control.

```bash
git init
```

--------------------------------

### Initialize npm Project

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/shadow-idea-notes.md

Initialize a new npm project to manage JavaScript dependencies.

```bash
npm init
```

--------------------------------

### Demonstrate All CitySDK Parameters

Source: https://context7.com/uscensusbureau/citysdk/llms.txt

Illustrates the usage of all available parameters for the `census` function, including vintage, geoHierarchy with lat/lng, sourcePath, values, predicates, geoResolution, and statsKey.

```javascript
import census from 'citysdk'

// All parameter types demonstrated
census(
  {
    vintage: 2019,                          // int or string
    geoHierarchy: {
      state: { lat: 38.9, lng: -77.0 },    // lat/lng geocoding
      county: '*',                          // wildcard descendant
    },
    sourcePath: ['acs', 'acs5'],            // ACS 5-year estimates
    values: ['B01001_001E', 'NAME'],        // total pop + geographic name
    predicates: { B01001_001E: '50000:' }, // only counties with pop >= 50,000
    geoResolution: '500k',
    statsKey: process.env.CENSUS_API_KEY,
  },
  (err, res) => {
    if (err) return console.error(err)
    // GeoJSON FeatureCollection of counties in the target state
    // with B01001_001E >= 50,000, boundaries merged with statistics
    console.log(res.features.map(f => ({
      name: f.properties.NAME,
      pop: f.properties.B01001_001E,
    })))
  }
)
```

--------------------------------

### Get AWS Account ID

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/src/configs/geojson/annualrefresh.md

Retrieves the AWS Account ID associated with the current IAM user credentials configured in the AWS CLI.

```shell
aws sts get-caller-identity --query "Account" --output text
```

--------------------------------

### Connect to REPL Server in VSCode

Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/README.md

Instructions for connecting VSCode's Calva extension to a running shadow-cljs REPL server. Requires specifying the project type and nREPL port.

```bash
ctrl + shift + p
```

--------------------------------

### Call WMS with State and County GeoHierarchy

Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md

Example of calling the WMS service with a specific state defined by coordinates and fetching all counties within that state.

```javascript
{
  "vintage": 2014,
  "geoHierarchy": { "state": { "lat": 28.2639, "lng": -80.7214 }, "county": '*' }
}
```

--------------------------------

### Initialize Mapbox GL JS Map

Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/mapbox/with-mapbox-gl_geocoding/index.html

Sets up a basic Mapbox GL JS map. Ensure you have a Mapbox access token configured.

```html



    
    Display a map
    
    
    


    
``` -------------------------------- ### Get Census Statistics by ID with API Key Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md Similar to fetching statistics by ID, but includes the `statsKey` parameter, which is necessary for high-volume data requests. ```APIDOC ## Get Census Statistics by ID (with API Key) ### Description Similar to fetching statistics by ID, but includes the `statsKey` parameter, which is necessary for high-volume data requests. ### Method `census` function call ### Parameters #### Required Parameters - **vintage** (number) - The year of the data. - **geoHierarchy** (object) - Specifies the geographic boundaries for the query. Example: `{ county: { lat: 28.2639, lng: -80.7214 } }`. - **sourcePath** (array of strings) - The path to the survey and/or source of the statistics. Example: `['cbp']`. - **values** (array of strings) - The identifiers of the statistics to retrieve. Example: `['ESTAB']`. - **statsKey** (string) - An API key required for making more than 500 calls per day. ### Request Example ```js census( { vintage: 2015, // required geoHierarchy: { // required county: { lat: 28.2639, lng: -80.7214, }, }, sourcePath: ['cbp'], // required values: ['ESTAB'], // required statsKey: '', // required for > 500 calls per day }, (err, res) => console.log(res) ) ``` ### Response #### Success Response (JSON) Returns an array of JSON objects, where each object contains the requested statistical values and geographic identifiers. #### Response Example ```json [{"ESTAB":13648,"state":"12","county":"009"}] ``` ``` -------------------------------- ### Parameters Overview Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md Overview of each argument parameter that can be passed into CitySDK. ```APIDOC ## Parameters Brief overview of each argument parameter that can be passed into CitySDK | Parameter | Type | Description | [Geocodes] | [Stats] | [GeoJSON] | [GeoJSON with Stats] | | --------------- | ----------- | ------------------------------------------------------------------ | :--------: | :-----: | :-------: | :------------------: | | `vintage` | `int`/`str` | The reference year (typically release year) of the data | ✔ | ✔ | ✔ | ✔ | | `geoHierarchy` | `object` | The geographic scope and hierarchical path to the data | ✔ | ✔ | ✔ | ✔ | | `sourcePath` | `array` | Refers to the [Census product] of interest | | ✔ | | ✔ | | `values` | `array` | For statistics, `values` request counts/estimates via variable IDs | | ✔ | | ✔ | | `geoResolution` | `str` | [Resolution] of GeoJSON (`"20m"`, `"5m"`, and `"500k"` available) | | | ✔ | ✔ | | `predicates` | `object` | Used as a filter available on some `values` | | ✔`*` | | ✔`*` | | `statsKey` | `str` | You may request a key for Census' statistics API [here] | | ✔`**` | | ✔`**` | [geocodes]: #census-geocoding [stats]: #getting-statistics [geojson]: #cartographic-geojson [geojson with stats]: #geojson-with-stats [census product]: https://www.census.gov/data/developers/data-sets.html [here]: https://api.census.gov/data/key_signup.html [resolution]: #cartographic-geojson `*` : optional `**` : optional for < 500 requests daily ``` -------------------------------- ### Highlighting with Web Workers (Main Script) Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/assets/highlight/README.md In the main script, set up an event listener for 'load' to query the code element, create a worker, and handle messages from it. ```javascript addEventListener('load', function() { var code = document.querySelector('#code'); var worker = new Worker('worker.js'); worker.onmessage = function(event) { code.innerHTML = event.data; } worker.postMessage(code.textContent); }) ``` -------------------------------- ### Get GeoJSON for Counties within a State Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md Fetches GeoJSON boundary data for all counties within a state, identified by a given coordinate. Uses a '500k' geoResolution. ```javascript { "vintage": 2014, "geoHierarchy": { "state": { "lat": 28.2639, "lng": -80.7214 }, "county": "*" }, "geoResolution": "500k" } ``` -------------------------------- ### Build CitySDK for NPM Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/README.md Command to build the CitySDK library for distribution via NPM. This step requires ensuring the `$default` flag is correctly set for `isomorphic-unfetch`. ```bash npm run build ``` -------------------------------- ### Custom Initialization with jQuery Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/assets/highlight/README.md For more control, use highlightBlock within a jQuery document ready function to highlight specific code blocks. ```javascript $(document).ready(function() { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); ``` -------------------------------- ### Get Single County Stats with Population Filter Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md Retrieves statistics for a single county, filtering out any county with a population under 100,000. Uses ACS 5-year data. ```javascript { "vintage": 2016, "geoHierarchy": { "county": { "lat": 28.2639, "lng": -80.7214 } }, "sourcePath": [ "acs", "acs5" ], "values": [ "B01001_001E" ] "predicates": { "B00001_001E": "0:100000" }, } ``` -------------------------------- ### Import CitySDK (ESM vs CommonJS) Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md Demonstrates how to import the CitySDK library depending on your project's module system. For v2.3+, use ESM imports. Older versions used CommonJS. ```javascript // 2.2.x or below const census = require('citysdk') // 2.3.x or above import census from 'citysdk' ``` -------------------------------- ### Generate Full File Paths for Conversion Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/src/configs/geojson/annualrefresh.md This command-line utility generates a list of all files with their full paths within the current directory and its subdirectories, saving the output to a text file. ```shell dir/s/b * > paths_full.txt ``` -------------------------------- ### Get Census Statistics by ID Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/public/census/README.md Retrieves statistical values (e.g., estimates) for a specified geographic area and source path. This is the primary method for fetching census data. ```APIDOC ## Get Census Statistics by ID ### Description Retrieves statistical values (e.g., estimates) for a specified geographic area and source path. This is the primary method for fetching census data. ### Method `census` function call ### Parameters #### Required Parameters - **vintage** (number) - The year of the data. - **geoHierarchy** (object) - Specifies the geographic boundaries for the query. Example: `{ county: { lat: 28.2639, lng: -80.7214 } }`. - **sourcePath** (array of strings) - The path to the survey and/or source of the statistics. Example: `['cbp']`. - **values** (array of strings) - The identifiers of the statistics to retrieve. Example: `['ESTAB']`. #### Optional Parameters - **statsKey** (string) - An API key required for making more than 500 calls per day. ### Request Example ```js census( { vintage: 2015, // required geoHierarchy: { // required county: { lat: 28.2639, lng: -80.7214, }, }, sourcePath: ['cbp'], // required values: ['ESTAB'], // required }, (err, res) => console.log(res) ) ``` ### Response #### Success Response (JSON) Returns an array of JSON objects, where each object contains the requested statistical values and geographic identifiers. #### Response Example ```json [{"ESTAB":13648,"state":"12","county":"009"}] ``` ``` -------------------------------- ### Request All Descendant Geographies within a Coordinate Area Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md This example shows how to request all descendant geographies of a specific type within a given coordinate. Use the '*' syntax to signify all descendants. ```javascript import census from 'citysdk' census( { vintage: '2015', // required geoHierarchy: { // required state: { lat: 28.2639, lng: -80.7214, }, county: '*', // <- syntax = "" : "*" }, }, (err, res) => console.log(res) ) // result -> {"vintage":"2015","geoHierarchy":{"state":"12","county":"*"}} ``` -------------------------------- ### Check for broken links recursively excluding JSON files Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/src/configs/discovery/notes.md Use `blc` to recursively check for broken links starting from a given URL. Excludes any links ending with '.json'. ```bash blc https://api.census.gov/data.html -r -o --exclude *json ``` -------------------------------- ### Configure Calva REPL Connection Source: https://github.com/uscensusbureau/citysdk/blob/master/v2/README.md Steps to configure the Calva extension in VSCode to connect to a shadow-cljs REPL server. This involves selecting the project type, providing the nREPL port, and choosing the build target. ```bash select a project type: `shadow-cljs` ``` ```bash add [port to nREPL](.nrepl-port): `localhost:3333` ``` ```bash select which build to connect to: `node-repl` ``` -------------------------------- ### Create Choropleth Map with Mapbox GL JS Source: https://context7.com/uscensusbureau/citysdk/llms.txt Use CitySDK to fetch GeoJSON data and create a choropleth map using Mapbox GL JS. Requires Mapbox access token and CitySDK/Chroma.js imports. Fetches GINI index for US counties. ```javascript import census from 'citysdk' import mapboxgl from 'mapbox-gl' import chroma from 'chroma-js' mapboxgl.accessToken = '' const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/light-v10', center: { lat: 37.09, lng: -95.71 }, zoom: 3, }) function censusPromise(args) { return new Promise((resolve, reject) => { census(args, (err, res) => (err ? reject(err) : resolve(res))) }) } map.on('load', async () => { const geojson = await censusPromise({ vintage: '2017', geoHierarchy: { county: '*' }, sourcePath: ['acs', 'acs5'], values: ['B19083_001E'], // GINI index statsKey: process.env.CENSUS_API_KEY, geoResolution: '500k', }) const values = geojson.features.map(f => f.properties.B19083_001E).filter(Boolean) const breaks = chroma.limits(values, 'q', 5) const colorScale = chroma.scale('YlOrRd').domain([breaks[0], breaks[breaks.length - 1]]) const stops = breaks.map(v => [v, colorScale(v).hex()]) map.addSource('census', { type: 'geojson', data: geojson }) map.addLayer({ id: 'counties-choropleth', type: 'fill', source: 'census', paint: { 'fill-color': { property: 'B19083_001E', stops }, 'fill-opacity': 0.75, 'fill-outline-color': '#ffffff', }, }) }) ``` -------------------------------- ### Get Timeseries Data Source: https://github.com/uscensusbureau/citysdk/blob/master/README.md Use this snippet to retrieve timeseries data for statistical purposes only. Mapping timeseries data is unsupported. Ensure 'vintage' is set to 'timeseries' and 'sourcePath' is specified. ```javascript census( { vintage: 'timeseries', // required geoHierarchy: { // required us: '*', }, sourcePath: ['asm', 'industry'], // required values: ['EMP', 'NAICS_TTL', 'GEO_TTL'], predicates: { time: '2016', NAICS: '31-33' }, }, (err, res) => console.log(res) ) /* result: [{"EMP": 11112764, "NAICS_TTL": "Manufacturing", "GEO_TTL": "United States", "time": "2016", "NAICS": "31-33", "us":"1"}] */ ``` -------------------------------- ### Configure Class Prefix Source: https://github.com/uscensusbureau/citysdk/blob/master/examples/assets/highlight/CHANGES.md To suppress the new default class prefixing behavior (e.g., `hljs-`), initialize Highlight.js with `classPrefix: ''`. ```html ``` -------------------------------- ### CitySDK Core Function Basic Usage with Callback Source: https://context7.com/uscensusbureau/citysdk/llms.txt Basic usage of the CitySDK census function with a standard Node.js callback. This example fetches statistical data and merges it into GeoJSON features. ```javascript import census from 'citysdk' // Basic usage with callback census( { vintage: 2017, geoHierarchy: { state: '51', county: '*' }, sourcePath: ['acs', 'acs5'], values: ['B19083_001E'], statsKey: '', geoResolution: '500k', }, (err, res) => { if (err) { console.error('CitySDK error:', err) return } // res is a GeoJSON FeatureCollection with B19083_001E merged into properties console.log(res.type) // "FeatureCollection" console.log(res.features[0].properties.B19083_001E) // e.g. 0.4512 } ) ```