You are here

public function GoogleGeocodingAPI::reverseGeocode in Geolocation Field 8.2

Same name and namespace in other branches
  1. 8.3 modules/geolocation_google_maps/src/Plugin/geolocation/Geocoder/GoogleGeocodingAPI.php \Drupal\geolocation_google_maps\Plugin\geolocation\Geocoder\GoogleGeocodingAPI::reverseGeocode()

Reverse geocode an address.

Intended return subject to available data:

[
  'organization' => '',
  'address_line1' => '',
  'address_line2' => '',
  'postal_code' => '',
  'sorting_code' => '',
  'dependent_locality' => [],
  'locality' => [],
  'administrative_area' => [],
  'country' => [],
  'formatted_address' => '',
];

Parameters

float $latitude: Latitude to reverse geocode.

float $longitude: Longitude to reverse geocode.

Return value

array||null Address or NULL.

Overrides GeocoderBase::reverseGeocode

File

modules/geolocation_google_maps/src/Plugin/geolocation/Geocoder/GoogleGeocodingAPI.php, line 138

Class

GoogleGeocodingAPI
Provides the Google Geocoding API.

Namespace

Drupal\geolocation_google_maps\Plugin\geolocation\Geocoder

Code

public function reverseGeocode($latitude, $longitude) {
  $config = \Drupal::config('geolocation_google_maps.settings');
  $request_url = GoogleMaps::$GOOGLEMAPSAPIURLBASE;
  if ($config
    ->get('china_mode')) {
    $request_url = GoogleMaps::$GOOGLEMAPSAPIURLBASECHINA;
  }
  $request_url .= '/maps/api/geocode/json?latlng=' . (double) $latitude . ',' . (double) $longitude;
  if (!empty($config
    ->get('google_map_api_server_key'))) {
    $request_url .= '&key=' . $config
      ->get('google_map_api_server_key');
  }
  elseif (!empty($config
    ->get('google_map_api_key'))) {
    $request_url .= '&key=' . $config
      ->get('google_map_api_key');
  }
  if (!empty($config
    ->get('google_map_custom_url_parameters')['language'])) {
    $request_url .= '&language=' . $config
      ->get('google_map_custom_url_parameters')['language'];
  }
  try {
    $result = Json::decode(\Drupal::httpClient()
      ->request('GET', $request_url)
      ->getBody());
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  if ($result['status'] != 'OK' || empty($result['results'][0]['geometry'])) {
    if (isset($result['error_message'])) {
      \Drupal::logger('geolocation')
        ->error(t('Unable to reverse geocode "@latitude, $longitude" with error: "@error". Request URL: @url', [
        '@latitude' => $latitude,
        '@$longitude' => $longitude,
        '@error' => $result['error_message'],
        '@url' => $request_url,
      ]));
    }
    return FALSE;
  }
  if (empty($result['results'][0]['address_components'])) {
    return NULL;
  }
  $addressAtomicsMapping = [
    'streetNumber' => [
      'type' => 'street_number',
    ],
    'route' => [
      'type' => 'route',
    ],
    'locality' => [
      'type' => 'locality',
    ],
    'county' => [
      'type' => 'administrative_area_level_2 ',
    ],
    'postalCode' => [
      'type' => 'postal_code',
    ],
    'adninistrativeArea' => [
      'type' => 'administrative_area_level_1 ',
    ],
    'country' => [
      'type' => 'country',
    ],
    'countryCode' => [
      'type' => 'country',
      'short' => TRUE,
    ],
    'postalTown' => [
      'type' => 'postal_town',
    ],
    'neighborhood' => [
      'type' => 'neighborhood',
    ],
    'premise' => [
      'type' => 'premise',
    ],
    'political' => [
      'type' => 'political',
    ],
  ];
  $address_atomics = [];
  foreach ($result['results'][0]['address_components'] as $component) {
    foreach ($addressAtomicsMapping as $atomic => $google_format) {
      if ($google_format['type'] == $component['types'][0]) {
        if (!empty($google_format['short'])) {
          $address_atomics[$atomic] = $component['short_name'];
        }
        else {
          $address_atomics[$atomic] = $component['long_name'];
        }
      }
    }
  }
  return [
    'atomics' => $address_atomics,
    'elements' => $this
      ->addressElements($address_atomics),
    'string' => empty($result['results'][0]['formatted_address']) ? '' : $result['results'][0]['formatted_address'],
  ];
}