# Pelias Geo Field

A Drupal custom field module that provides geocoding functionality using the Pelias API, with support for both Geocode Earth SaaS service and self-hosted Pelias instances.

## Features

- **Autocomplete geocoding field** with real-time search suggestions
- **Flexible API integration** - works with Geocode Earth or self-hosted Pelias
- **Rich data storage** - stores both raw JSON and parsed structured data
- **Configurable field mappings** - extract specific fields from API responses
- **Performance optimized** - includes debouncing, caching, and rate limiting
- **Customizable formatters** - multiple display options for field output
- **Admin interface** - easy configuration and API testing

## Installation

1. Download and place the module in your `modules/custom/` directory
2. Enable the module: `drush en pelias_geo_field`
3. Configure the module at `/admin/config/content/pelias-geo-field`

## Configuration

### API Settings

1. **API Endpoint**: Set to `https://api.geocode.earth/v1` for Geocode Earth or your self-hosted URL
2. **API Key**: Required for Geocode Earth (format: `ge-xxxxxxxxxxxxxxxx`)
3. **Performance Settings**: Configure timeout, rate limits, debounce delay, and caching

### Data Sources and Layers

Configure which data sources and place types are available:

- **Sources**: OSM, OpenAddresses, GeoNames, Who's On First
- **Layers**: venue, address, street, country, region, locality, etc.

## Usage

### Adding the Field

1. Go to any content type's "Manage fields" page
2. Add a new field of type "Pelias Geo Field"
3. Configure field settings:
   - Maximum suggestions
   - Minimum characters for search
   - Focus point (lat/lon) for biased results
   - Boundary country restriction
   - Allowed sources and layers
   - Parsed field mappings

### Field Settings

#### Parsed Field Mappings

Configure which data to extract from the raw JSON response:

```
Field Name: city
JSON Path: properties.locality

Field Name: latitude  
JSON Path: geometry.coordinates.1

Field Name: longitude
JSON Path: geometry.coordinates.0
```

### Display Formatters

The module provides several formatter options:

- **Label only**: Just the location name
- **Label with context**: Name with city, region, country
- **Full address**: Complete address components
- **Coordinates only**: Just lat/lon coordinates  
- **Custom template**: Use tokens like `[name], [locality] ([latitude], [longitude])`

#### Formatter Filters

- **Data source filter**: Only show results from specific sources
- **Data layer filter**: Only show specific place types

## API Integration

### Geocode Earth

```php
// Example configuration
$config = [
  'api_endpoint' => 'https://api.geocode.earth/v1',
  'api_key' => 'ge-1234567890abcdef',
];
```

### Self-hosted Pelias

```php
// Example configuration  
$config = [
  'api_endpoint' => 'https://your-pelias-server.com/v1',
  'api_key' => '', // Usually not needed for self-hosted
];
```

## Data Storage

The field stores three values:

1. **value**: Display text shown to users
2. **raw_data**: Complete JSON response from Pelias API
3. **parsed_data**: Structured data based on field mappings

### Accessing Data Programmatically

```php
// Get field value
$field_item = $node->field_location->first();

// Get parsed data as array
$parsed = $field_item->getParsedData();
$city = $parsed['city'] ?? '';
$lat = $parsed['latitude'] ?? '';

// Get raw API response
$raw = $field_item->getRawData(); 
$confidence = $raw['properties']['confidence'] ?? '';
```

## JavaScript API

### Autocomplete Behavior

The autocomplete functionality uses:
- **Debouncing**: Configurable delay before API calls
- **Keyboard navigation**: Arrow keys, Enter, Escape
- **Loading states**: Visual feedback during searches
- **Error handling**: Graceful failure recovery

### Events

```javascript
// Listen for selection changes
$('.pelias-geo-autocomplete').on('change', function() {
  var rawData = $(this).siblings('.pelias-geo-raw-data').val();
  var parsedData = $(this).siblings('.pelias-geo-parsed-data').val();
  // Handle data...
});
```

## Theming

### CSS Classes

- `.pelias-suggestions-container`: Main suggestions wrapper
- `.pelias-suggestions`: Suggestions list
- `.pelias-suggestion-item`: Individual suggestion
- `.pelias-suggestion-highlighted`: Currently highlighted item
- `.pelias-suggestion-loading`: Loading state
- `.pelias-suggestion-empty`: No results state
- `.pelias-suggestion-error`: Error state

### Customizing Appearance

Override the default CSS in your theme:

```css
.pelias-suggestions {
  border-color: your-brand-color;
}

.pelias-suggestion-highlighted {
  background-color: your-highlight-color;
}
```

## Performance

### Caching

- API responses are cached based on query and options
- Configurable cache lifetime (default: 1 hour)
- Set to 0 to disable caching

### Rate Limiting

- Client-side debouncing prevents excessive API calls
- Server-side rate limiting protects your API quota
- Configurable delays and limits

### Best Practices

1. Set appropriate minimum character lengths (2-3 chars)
2. Use focus points to bias results to relevant areas
3. Filter by country/sources/layers to reduce result sets
4. Enable caching for better performance
5. Monitor your API usage and adjust rate limits

## Troubleshooting

### API Connection Issues

1. Test your configuration at `/admin/config/content/pelias-geo-field`
2. Check the API endpoint URL format
3. Verify API key format for Geocode Earth (`ge-` prefix)
4. Review error logs for detailed failure information

### Common Issues

- **No suggestions appearing**: Check minimum character setting and API connectivity
- **Slow responses**: Adjust debounce delay and enable caching
- **Rate limit errors**: Reduce rate limit setting or increase debounce delay
- **Empty results**: Verify sources/layers configuration matches your API

## Requirements

- Drupal 9, 10, or 11
- PHP 7.4 or higher
- Guzzle HTTP client (included in Drupal core)

## License

This module is licensed under the GPL v2 or later.

## Support

For issues and feature requests, please use the project's issue queue.