You are here

GeoCodeAddressForm.php in IP Geolocation Views & Maps 8

File

src/Form/GeoCodeAddressForm.php
View source
<?php

namespace Drupal\ip_geoloc\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\ip_geoloc\Services\IpGeoLocSession;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\ip_geoloc\Services\IpGeoLocAPI;
use Drupal\geocoder\Geocoder;

/**
 * Form to reverse geocode a address to latitud and Longitude.
 */
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();
  }

}

Classes

Namesort descending Description
GeoCodeAddressForm Form to reverse geocode a address to latitud and Longitude.