A robust, POSIX-compliant shell script SDK for the OpenCage Geocoding API. Perfect for DevOps automation, CI/CD pipelines, and system administration tasks.
- ✅ Forward Geocoding: Convert addresses to coordinates
- ✅ Reverse Geocoding: Convert coordinates to addresses
- ✅ Batch Processing: Process multiple addresses from files
- ✅ Error Handling: Comprehensive HTTP and API error handling
- ✅ Rate Limiting: Built-in request throttling
- ✅ Logging: Configurable verbose logging with colors
- ✅ POSIX Compliant: Works with bash, zsh, dash, and other shells
- ✅ Dependencies: Only requires
curlandjq(widely available)
# Download the SDK
curl -O https://raw.githubusercontent.com/geonot/opencage-bash-sdk/main/opencage.sh
chmod +x opencage.sh
# Or clone the repository
git clone https://github.com/geonot/opencage-bash-sdk.git
cd opencage-bash-sdkSign up for a free API key at OpenCage Data.
# Test connectivity
./opencage.sh ping
# Forward geocoding
./opencage.sh forward "Berlin, Germany"
# Reverse geocoding
./opencage.sh reverse "52.520008,13.404954"
# Get coordinates only
./opencage.sh coords "1600 Amphitheatre Parkway, Mountain View, CA"
# Get address only
./opencage.sh address "37.422,-122.084"# Load functions into your shell
source opencage.sh
# Set your API key
export OPENCAGE_API_KEY="your-32-character-api-key-here"
# Use the functions
result=$(opencage_forward "London, UK")
echo "$result" | opencage_pretty_print
coordinates=$(opencage_get_coordinates "Paris, France")
echo "Paris coordinates: $coordinates"| Variable | Default | Description |
|---|---|---|
OPENCAGE_API_KEY |
- | Your OpenCage API key (required) |
OPENCAGE_VERBOSE |
0 | Set to 1 for verbose logging |
OPENCAGE_TIMEOUT |
30 | HTTP request timeout in seconds |
OPENCAGE_DEFAULT_FORMAT |
json | Default response format |
OPENCAGE_DEFAULT_LANGUAGE |
en | Default language for results |
OPENCAGE_DEFAULT_LIMIT |
10 | Default number of results |
export OPENCAGE_API_KEY="your-api-key-here"
export OPENCAGE_VERBOSE=1
export OPENCAGE_TIMEOUT=60
source opencage.shConvert an address to coordinates.
result=$(opencage_forward "New York City" "your-api-key" 5 "en")Convert coordinates to an address.
result=$(opencage_reverse "40.7589,-73.9851" "your-api-key" "en")Forward geocoding with comprehensive OpenCage API parameter support.
Supported Parameters:
limit=N- Maximum number of resultslanguage=LANG- Language for resultscountrycode=CC- Restrict to country codes (comma-separated)bounds=BOUNDS- Restrict to bounding box (minlat,minlng,maxlat,maxlng)proximity=LAT,LNG- Bias results towards coordinatesabbrv=1- Use abbreviated address formatmin_confidence=N- Minimum confidence level (1-10)no_annotations=1- Skip annotationsno_dedupe=1- Skip deduplicationno_record=1- Skip recording queryroadinfo=1- Include road informationadd_request=1- Include request details in response
# Basic usage
opencage_forward_advanced "London" "$API_KEY" countrycode=gb limit=5
# Multiple parameters
opencage_forward_advanced "Paris" "$API_KEY" bounds=48,2,49,3 abbrv=1 language=fr
# Complex query
opencage_forward_advanced "coffee shop" "$API_KEY" proximity=40.7589,-73.9851 countrycode=us min_confidence=5Reverse geocoding with comprehensive OpenCage API parameter support.
Supported Parameters:
language=LANG- Language for resultsabbrv=1- Use abbreviated address formatno_annotations=1- Skip annotationsno_record=1- Skip recording queryroadinfo=1- Include road informationadd_request=1- Include request details in response
# Basic usage
opencage_reverse_advanced "52.520008,13.404954" "$API_KEY" language=de abbrv=1
# With multiple options
opencage_reverse_advanced "40.7589,-73.9851" "$API_KEY" roadinfo=1 add_request=1Get just the coordinates for an address.
coords=$(opencage_get_coordinates "Tokyo, Japan")
echo "Tokyo is at: $coords"
# Output: Tokyo is at: 35.6762,139.6503Get just the formatted address for coordinates.
address=$(opencage_get_address "48.8566,2.3522")
echo "Address: $address"
# Output: Address: Paris, FranceProcess multiple addresses from a file.
# Create input file
echo -e "Berlin, Germany\nTokyo, Japan\nNew York, USA" > addresses.txt
# Batch geocode
opencage_batch_forward addresses.txt your-api-key results.txtTest API connectivity.
if opencage_ping; then
echo "API is reachable"
fiExtract coordinates from API response.
result=$(opencage_forward "London")
coords=$(opencage_extract_coordinates "$result")Pretty print JSON response.
result=$(opencage_forward "London")
opencage_pretty_print "$result"#!/bin/bash
source opencage.sh
# Geocode server locations from configuration
while read -r server_address; do
coordinates=$(opencage_get_coordinates "$server_address")
if [[ $? -eq 0 ]]; then
echo "Server at $server_address is located at: $coordinates"
# Add to monitoring system, etc.
else
echo "Failed to geocode: $server_address"
fi
done < server_locations.txt#!/bin/bash
# Deploy script with location validation
source opencage.sh
DEPLOYMENT_ADDRESS="1600 Amphitheatre Parkway, Mountain View, CA"
REQUIRED_COORDINATES="37.4220,-122.0841"
actual_coords=$(opencage_get_coordinates "$DEPLOYMENT_ADDRESS")
if [[ "$actual_coords" == "$REQUIRED_COORDINATES" ]]; then
echo "✅ Deployment location verified"
# Continue deployment
else
echo "❌ Location mismatch: expected $REQUIRED_COORDINATES, got $actual_coords"
exit 1
fi#!/bin/bash
source opencage.sh
# Process access logs with IP geolocation
while read -r log_line; do
ip=$(echo "$log_line" | cut -d' ' -f1)
# Use IP geolocation service to get coordinates, then reverse geocode
location=$(opencage_get_address "$coordinates")
echo "$log_line | Location: $location"
done < access.logThe SDK provides comprehensive error handling for common scenarios:
- Network Issues: Connection timeouts, DNS failures
- API Errors: Invalid API key, quota exceeded, rate limiting
- Data Issues: Invalid coordinates, no results found
- Input Validation: Malformed addresses, missing parameters
All errors are logged with appropriate severity levels and return non-zero exit codes.
if ! opencage_forward "Invalid Address"; then
echo "Geocoding failed"
# Handle error appropriately
fiThe SDK requires only two common utilities:
- curl: For HTTP requests (usually pre-installed)
- jq: For JSON parsing
# Ubuntu/Debian
sudo apt-get install curl jq
# CentOS/RHEL
sudo yum install curl jq
# macOS
brew install curl jq
# Alpine Linux
apk add curl jqThe OpenCage API has rate limits. The SDK includes built-in throttling for batch operations:
- Batch processing automatically adds 100ms delays between requests
- Monitor your usage in the OpenCage Dashboard
- Consider caching results for repeated queries
Run the test suite:
./test.shThe test suite requires:
- Valid OpenCage API key set in
OPENCAGE_API_KEY - Internet connectivity
- All dependencies installed
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
MIT License
Copyright (c) 2025 Rome Stone
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.