You are here

class GoogleGeocodingAPI 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

Provides the Google Geocoding API.

Plugin annotation


@Geocoder(
  id = "google_geocoding_api",
  name = @Translation("Google Geocoding API"),
  description = @Translation("You do require an API key for this plugin to work."),
  locationCapable = true,
  boundaryCapable = true,
  frontendCapable = true,
  reverseCapable = true,
)

Hierarchy

Expanded class hierarchy of GoogleGeocodingAPI

File

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

Namespace

Drupal\geolocation_google_maps\Plugin\geolocation\Geocoder
View source
class GoogleGeocodingAPI extends GoogleGeocoderBase {

  /**
   * {@inheritdoc}
   */
  public function formAttachGeocoder(array &$render_array, $element_name) {
    parent::formAttachGeocoder($render_array, $element_name);
    $config = \Drupal::config('geolocation_google_maps.settings');
    $render_array['#attached'] = BubbleableMetadata::mergeAttachments($render_array['#attached'], [
      'library' => [
        'geolocation_google_maps/geocoder.googlegeocodingapi',
      ],
    ]);
    if (!empty($config
      ->get('google_map_custom_url_parameters')['region'])) {
      $render_array['#attached']['drupalSettings']['geolocation']['geocoder'][$this
        ->getPluginId()]['region'] = $config
        ->get('google_map_custom_url_parameters')['region'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function geocode($address) {
    $config = \Drupal::config('geolocation_google_maps.settings');
    if (empty($address)) {
      return FALSE;
    }
    if (!empty($config
      ->get('google_maps_base_url'))) {
      $request_url = $config
        ->get('google_maps_base_url');
    }
    elseif ($config
      ->get('china_mode')) {
      $request_url = GoogleMaps::$GOOGLEMAPSAPIURLBASECHINA;
    }
    else {
      $request_url = GoogleMaps::$GOOGLEMAPSAPIURLBASE;
    }
    $request_url .= '/maps/api/geocode/json?address=' . urlencode($address);
    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($this->configuration['component_restrictions'])) {
      $request_url .= '&components=';
      foreach ($this->configuration['component_restrictions'] as $component_id => $component_value) {
        $request_url .= $component_id . ':' . $component_value . '|';
      }
    }
    if (!empty($config
      ->get('google_map_custom_url_parameters')['language'])) {
      $request_url .= '&language=' . $config
        ->get('google_map_custom_url_parameters')['language'];
    }
    if (!empty($this->configuration['boundary_restriction']) && !empty($this->configuration['boundary_restriction']['south']) && !empty($this->configuration['boundary_restriction']['west']) && !empty($this->configuration['boundary_restriction']['north']) && !empty($this->configuration['boundary_restriction']['east'])) {
      $bounds = $this->configuration['boundary_restriction']['south'] . ',';
      $bounds .= $this->configuration['boundary_restriction']['west'] . '|';
      $bounds .= $this->configuration['boundary_restriction']['north'] . ',';
      $bounds .= $this->configuration['boundary_restriction']['east'];
      $request_url .= '&bounds=' . $bounds;
    }
    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 geocode "@address" with error: "@error". Request URL: @url', [
          '@address' => $address,
          '@error' => $result['error_message'],
          '@url' => $request_url,
        ]));
      }
      return FALSE;
    }
    return [
      'location' => [
        'lat' => $result['results'][0]['geometry']['location']['lat'],
        'lng' => $result['results'][0]['geometry']['location']['lng'],
      ],
      // TODO: Add viewport or build it if missing.
      'boundary' => [
        'lat_north_east' => empty($result['results'][0]['geometry']['viewport']) ? $result['results'][0]['geometry']['location']['lat'] + 0.005 : $result['results'][0]['geometry']['viewport']['northeast']['lat'],
        'lng_north_east' => empty($result['results'][0]['geometry']['viewport']) ? $result['results'][0]['geometry']['location']['lng'] + 0.005 : $result['results'][0]['geometry']['viewport']['northeast']['lng'],
        'lat_south_west' => empty($result['results'][0]['geometry']['viewport']) ? $result['results'][0]['geometry']['location']['lat'] - 0.005 : $result['results'][0]['geometry']['viewport']['southwest']['lat'],
        'lng_south_west' => empty($result['results'][0]['geometry']['viewport']) ? $result['results'][0]['geometry']['location']['lng'] - 0.005 : $result['results'][0]['geometry']['viewport']['southwest']['lng'],
      ],
      'address' => empty($result['results'][0]['formatted_address']) ? '' : $result['results'][0]['formatted_address'],
    ];
  }

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

}

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::getSettings public function Return plugin settings.
GeocoderBase::processOptionsForm public function Process the form built above. Overrides GeocoderInterface::processOptionsForm
GoogleGeocoderBase::$googleMapsProvider protected property Google maps provider.
GoogleGeocoderBase::create public static function Creates an instance of the plugin. Overrides GeocoderBase::create
GoogleGeocoderBase::getDefaultSettings protected function Return plugin default settings. Overrides GeocoderBase::getDefaultSettings
GoogleGeocoderBase::getOptionsForm public function Return additional options form. Overrides GeocoderBase::getOptionsForm
GoogleGeocoderBase::__construct public function GoogleGeocoderBase constructor. Overrides GeocoderBase::__construct
GoogleGeocodingAPI::formAttachGeocoder public function Attach geocoding logic to input element. Overrides GoogleGeocoderBase::formAttachGeocoder
GoogleGeocodingAPI::geocode public function Geocode an address. Overrides GeocoderBase::geocode
GoogleGeocodingAPI::reverseGeocode public function Reverse geocode an address. Overrides GeocoderBase::reverseGeocode
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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.