public function Nominatim::reverseGeocode in Geolocation Field 8.2
Same name and namespace in other branches
- 8.3 modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Nominatim.php \Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder\Nominatim::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_leaflet/ src/ Plugin/ geolocation/ Geocoder/ Nominatim.php, line 85  
Class
- Nominatim
 - Provides the Nominatim API.
 
Namespace
Drupal\geolocation_leaflet\Plugin\geolocation\GeocoderCode
public function reverseGeocode($latitude, $longitude) {
  $request_url_base = $this
    ->getRequestUrlBase();
  $url = Url::fromUri($request_url_base . '/reverse/', [
    'query' => [
      'lat' => $latitude,
      'lon' => $longitude,
      'email' => $this
        ->getRequestEmail(),
      'limit' => 1,
      'format' => 'json',
      'connect_timeout' => 5,
      'addressdetails' => 1,
      'zoom' => 18,
    ],
  ]);
  try {
    $result = Json::decode(\Drupal::httpClient()
      ->get($url
      ->toString())
      ->getBody());
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  if (empty($result['address'])) {
    return FALSE;
  }
  $address_atomics = [];
  foreach ($result['address'] as $component => $value) {
    switch ($component) {
      case 'house_number':
        $address_atomics['houseNumber'] = $value;
        break;
      case 'road':
        $address_atomics['road'] = $value;
        break;
      case 'town':
        $address_atomics['village'] = $value;
        break;
      case 'city':
        $address_atomics['city'] = $value;
        break;
      case 'county':
        $address_atomics['county'] = $value;
        break;
      case 'postcode':
        $address_atomics['postcode'] = $value;
        break;
      case 'state':
        $address_atomics['state'] = $value;
        break;
      case 'country':
        $address_atomics['country'] = $value;
        break;
      case 'country_code':
        $address_atomics['countryCode'] = strtoupper($value);
        break;
      case 'suburb':
        $address_atomics['suburb'] = $value;
        break;
    }
  }
  return [
    'atomics' => $address_atomics,
    'elements' => $this
      ->addressElements($address_atomics),
    'formatted_address' => empty($result['display_name']) ? '' : $result['display_name'],
  ];
}