You are here

class Nominatim in Geolocation Field 8.3

Same name and namespace in other branches
  1. 8.2 modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Nominatim.php \Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder\Nominatim

Provides the Nominatim API.

Plugin annotation


@Geocoder(
  id = "nominatim",
  name = @Translation("Nominatim"),
  description = @Translation("See https://wiki.openstreetmap.org/wiki/Nominatim for details."),
  locationCapable = true,
  boundaryCapable = true,
  frontendCapable = false,
  reverseCapable = true,
)

Hierarchy

Expanded class hierarchy of Nominatim

File

modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Nominatim.php, line 24

Namespace

Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder
View source
class Nominatim extends GeocoderBase implements GeocoderInterface {

  /**
   * Nominatim base URL.
   *
   * @var string
   */
  protected static $nominatimBaseUrl = 'https://nominatim.openstreetmap.org';

  /**
   * {@inheritdoc}
   */
  public function geocode($address) {
    if (empty($address)) {
      return FALSE;
    }
    $request_url_base = $this
      ->getRequestUrlBase();
    $url = Url::fromUri($request_url_base . '/search/' . $address, [
      'query' => [
        'email' => $this
          ->getRequestEmail(),
        'limit' => 1,
        'format' => 'json',
        'connect_timeout' => 5,
      ],
    ]);
    try {
      $result = Json::decode(\Drupal::httpClient()
        ->get($url
        ->toString())
        ->getBody());
    } catch (RequestException $e) {
      watchdog_exception('geolocation', $e);
      return FALSE;
    }
    $location = [];
    if (empty($result[0])) {
      return FALSE;
    }
    else {
      $location['location'] = [
        'lat' => $result[0]['lat'],
        'lng' => $result[0]['lon'],
      ];
    }
    if (!empty($result[0]['boundingbox'])) {
      $location['boundary'] = [
        'lat_north_east' => $result[0]['boundingbox'][1],
        'lng_north_east' => $result[0]['boundingbox'][3],
        'lat_south_west' => $result[0]['boundingbox'][0],
        'lng_south_west' => $result[0]['boundingbox'][2],
      ];
    }
    if (!empty($result[0]['display_name'])) {
      $location['address'] = $result[0]['display_name'];
    }
    return $location;
  }

  /**
   * {@inheritdoc}
   */
  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'],
    ];
  }

  /**
   * Retrieve base URL from setting or default.
   *
   * @return string
   *   Base URL.
   */
  protected function getRequestUrlBase() {
    $config = \Drupal::config('geolocation_leaflet.nominatim_settings');
    if (!empty($config
      ->get('nominatim_base_url'))) {
      $request_url = $config
        ->get('nominatim_base_url');
    }
    else {
      $request_url = self::$nominatimBaseUrl;
    }
    return $request_url;
  }

  /**
   * Nominatim should be called with a request E-Mail.
   *
   * @return string
   *   Get Request Email.
   */
  protected function getRequestEmail() {
    $config = \Drupal::config('geolocation_leaflet.nominatim_settings');
    if (!empty($config
      ->get('nominatim_email'))) {
      $request_email = $config
        ->get('nominatim_email');
    }
    else {
      $request_email = \Drupal::config('system.site')
        ->get('mail');
    }
    return $request_email;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
GeocoderBase::$countryFormatterManager protected property Country formatter manager.
GeocoderBase::addressElements protected function Get formatted address elements from atomics.
GeocoderBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
GeocoderBase::formAttachGeocoder public function Attach geocoding logic to input element. Overrides GeocoderInterface::formAttachGeocoder 4
GeocoderBase::getDefaultSettings protected function Return plugin default settings. 2
GeocoderBase::getOptionsForm public function Return additional options form. Overrides GeocoderInterface::getOptionsForm 2
GeocoderBase::getSettings public function Return plugin settings.
GeocoderBase::processOptionsForm public function Process the form built above. Overrides GeocoderInterface::processOptionsForm
GeocoderBase::__construct public function GoogleGeocoderBase constructor. Overrides PluginBase::__construct 1
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
Nominatim::$nominatimBaseUrl protected static property Nominatim base URL.
Nominatim::geocode public function Geocode an address. Overrides GeocoderBase::geocode
Nominatim::getRequestEmail protected function Nominatim should be called with a request E-Mail.
Nominatim::getRequestUrlBase protected function Retrieve base URL from setting or default.
Nominatim::reverseGeocode public function Reverse geocode an address. Overrides GeocoderBase::reverseGeocode
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.