You are here

public function Geocodio::geocode in Geolocation Field 8.3

Geocode an address.

Parameters

string $address: Address to geocode.

Return value

array||null Location or NULL.

Overrides GeocoderBase::geocode

File

modules/geolocation_geocodio/src/Plugin/geolocation/Geocoder/Geocodio.php, line 31

Class

Geocodio
Provides a Geocodio integration.

Namespace

Drupal\geolocation_geocodio\Plugin\geolocation\Geocoder

Code

public function geocode($address) {
  if (empty($address)) {
    return FALSE;
  }

  // Get config.
  $config = \Drupal::config('geolocation_geocodio.settings');
  $fields = $config
    ->get('fields');
  $location = [];

  // Set up connection to geocod.io.
  $geocoder = new GeocodioAPI();
  $key = KeyProvider::getKeyValue($config
    ->get('api_key'));
  $geocoder
    ->setApiKey($key);

  // Attempt to geolocate address.
  try {

    // If fields are defined in settings pull associated
    // metadata.
    if (!empty($fields)) {
      $fields = explode(',', $fields);
      $result = $geocoder
        ->geocode($address, $fields);
    }
    else {
      $result = $geocoder
        ->geocode($address);
    }
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  $results = $result->results[0] ?? FALSE;

  // If no results, return false.
  if (!$results) {
    return FALSE;
  }
  else {
    $location['location'] = [
      'lat' => $results->location->lat,
      'lng' => $results->location->lng,
    ];
  }

  // Add formatted address if it exists.
  if (!empty($results->formatted_address)) {
    $location['address'] = $results->formatted_address;
  }

  // Add metadata coming from fields if it exists.
  if (!empty($results->fields)) {
    $location['metadata'] = $results->fields;
  }
  return $location;
}