You are here

class GeoCodeAddressForm in IP Geolocation Views & Maps 8

Form to reverse geocode a address to latitud and Longitude.

Hierarchy

Expanded class hierarchy of GeoCodeAddressForm

File

src/Form/GeoCodeAddressForm.php, line 18

Namespace

Drupal\ip_geoloc\Form
View source
class GeoCodeAddressForm extends FormBase {
  protected $messenger;
  protected $moduleHandler;
  protected $ipGeolocSession;
  protected $configFactory;
  protected $api;
  protected $geocoder;

  /**
   * Constructs a \Drupal\ip_geoloc\Form\GeoCodeAddressForm object. Adds the dependency injection.
   */
  public function __construct(ConfigFactoryInterface $configFactory, MessengerInterface $messenger, ModuleHandler $moduleHandler, IpGeoLocSession $ipGeolocSession, IpGeoLocAPI $api, Geocoder $geocoder) {
    $this->configFactory = $configFactory;
    $this->messenger = $messenger;
    $this->moduleHandler = $moduleHandler;
    $this->ipGeolocSession = $ipGeolocSession;
    $this->api = $api;
    $this->geocoder = $geocoder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('messenger'), $container
      ->get('moduleHandler'), $container
      ->get('ip_geoloc.session'), $container
      ->get('ip_geoloc.api'), $container
      ->get('geocoder'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ip_geoloc_geocode_address';
  }

  /**
   * Geocode, using the Geocoder API, the submitted street address.
   *
   * Stores the geocoded lat/long on the session.
   * Modules may implement their own variations by implementing hook_form_alter()
   * and appending their own handler to $form['#submit'].
   *
   * @param array $form
   *   A form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form's current state.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Migration comment:  Part of ip_geoloc_set_location_form definition.
    $config = $this->configFactory
      ->get('ip_geoloc.settings');
    $location = $this->api
      ->getVisitorLocation();
    $is_address_editable = $config
      ->get('ip_geoloc_visitor_address_editable') ? $config
      ->get('ip_geoloc_visitor_address_editable') : TRUE;
    $form['street_address'] = [
      '#type' => 'textfield',
      '#title' => t('Current approximate address'),
      '#default_value' => isset($location['formatted_address']) ? $location['formatted_address'] : '',
      '#disabled' => !$is_address_editable,
    ];
    if ($is_address_editable) {
      $form['actions']['#type'] = 'actions';
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Refine'),
        '#button_type' => 'primary',
      ];
    }
    $form['#attributes']['class'][] = 'ip-geoloc-address';
    $form['#attached']['library'][] = 'ip_geoloc/client_css';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Migration comment:  Part of ip_geoloc_geocode for submiting ip_geoloc_set_location_form.
    if ($this->moduleHandler
      ->moduleExists('geocoder')) {

      // Use Google server-side API to retrieve lat/long from entered address.
      $plugins = [
        'googlemaps',
      ];
      $address = $form_state
        ->getValue('street_address');

      // Array of (ovverriding) options (@see Note* below)
      $options = [
        // Array of options.
        'googlemaps' => [],
      ];
      $addressCollection = $this->geocoder
        ->geocode($address, $plugins, $options);
      $point = $addressCollection
        ->get(0);
      if (!$point) {
        $this->messenger
          ->addMessage($this
          ->t('The address you entered could not be geocoded to a location.'), 'warning');
        return;
      }
      $location = [
        'provider' => 'user/google',
        'ip_address' => \Drupal::request()
          ->getClientIp(),
        'latitude' => $point
          ->getLatitude(),
        'longitude' => $point
          ->getLongitude(),
        'country' => $point
          ->getCountry(),
        'locality' => $point
          ->getLocality(),
        'formatted_address' => $point
          ->getStreetName() . ' ' . $point
          ->getStreetNumber(),
      ];

      // print_r($location);die();
      // Flatten the point object into a straight location array.

      /*foreach ($point->data['geocoder_address_components'] as $component) {
        if (!empty($component->long_name)) {
        $type = $component->types[0];
        $location[$type] = $component->long_name;
        if ($type == 'country' && !empty($component->short_name)) {
        $location['country_code'] = $component->short_name;
        }
        }
        }*/
      $this->ipGeolocSession
        ->setSessionValue('location', $location);
    }

    // Form always uses location from session.
    $form_state
      ->setRebuild();
  }

}

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
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
GeoCodeAddressForm::$api protected property
GeoCodeAddressForm::$configFactory protected property The config factory. Overrides FormBase::$configFactory
GeoCodeAddressForm::$geocoder protected property
GeoCodeAddressForm::$ipGeolocSession protected property
GeoCodeAddressForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
GeoCodeAddressForm::$moduleHandler protected property
GeoCodeAddressForm::buildForm public function Geocode, using the Geocoder API, the submitted street address. Overrides FormInterface::buildForm
GeoCodeAddressForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
GeoCodeAddressForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
GeoCodeAddressForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
GeoCodeAddressForm::__construct public function Constructs a \Drupal\ip_geoloc\Form\GeoCodeAddressForm object. Adds the dependency injection.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.