Geocoding Fundamentals
Geocoding converts addresses to geographic coordinates (latitude/longitude). Reverse geocoding does the opposite.
Forward Geocoding
Address → Coordinates
1"123 Main St, New York, NY 10001"2 ↓3{ lat: 40.7484, lng: -73.9967 }
Use cases:
- Plot customer locations on maps
- Calculate delivery distances
- Verify address existence
Reverse Geocoding
Coordinates → Address
1{ lat: 40.7484, lng: -73.9967 }2 ↓3"123 Main St, New York, NY 10001"
Use cases:
- Mobile app location sharing
- GPS coordinate conversion
- Location-based services
Free Geocoding APIs
| Service | Rate Limit | Key Required |
|---|---|---|
| Nominatim | 1/sec | No |
| GeoNames | 2000/hr | Username |
| OpenCage | 2500/day | Yes |
Using Nominatim
javascript1async function geocode(address) {2 const url = new URL('https://nominatim.openstreetmap.org/search');3 url.searchParams.set('q', address);4 url.searchParams.set('format', 'json');5 url.searchParams.set('limit', '1');67 const response = await fetch(url, {8 headers: { 'User-Agent': 'MyApp/1.0' }9 });1011 const data = await response.json();1213 if (data.length === 0) return null;1415 return {16 lat: parseFloat(data[0].lat),17 lng: parseFloat(data[0].lon),18 displayName: data[0].display_name19 };20}
Confidence Scores
Geocoding results include confidence indicators:
| Metric | Meaning |
|---|---|
| importance | 0-1 relevance score |
| class | Place type (building, road) |
| type | Specific type (house, street) |
javascript1function isHighConfidence(result) {2 return result.importance > 0.6 &&3 ['building', 'house'].includes(result.type);4}
Best Practices
- Normalize addresses first - Standardize before geocoding
- Cache results - Coordinates rarely change
- Handle failures - Graceful fallback
- Respect rate limits - Don't get blocked
- Validate results - Check confidence scores