Bennd

vendor/petrabarus/....../GooglePlacesAutocomplete.php

Dec 10th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2.  
  3. namespace PetraBarus\Yii2\GooglePlacesAutoComplete;
  4.  
  5. use yii\widgets\InputWidget;
  6. use yii\helpers\Html;
  7.  
  8.  
  9. class GooglePlacesAutoComplete extends InputWidget
  10. {
  11.  
  12.     const API_URL = '//maps.googleapis.com/maps/api/js?';
  13.  
  14.     public $libraries = 'places';
  15.  
  16.     public $sensor = true;
  17.  
  18.     public $language = 'en-US';
  19.     public $key      = null;
  20.  
  21.     public $autocompleteOptions = [];
  22.  
  23.     /**
  24.      * Renders the widget.
  25.      */
  26.     public function run()
  27.     {
  28.         $this->registerClientScript();
  29.         if ($this->hasModel()) {
  30.             echo Html::activeTextInput($this->model, $this->attribute, $this->options);
  31.         } else {
  32.             echo Html::textInput($this->name, $this->value, $this->options);
  33.         }
  34.     }
  35.  
  36.     /**
  37.      * Registers the needed JavaScript.
  38.      */
  39.     public function registerClientScript()
  40.     {
  41.         $elementId     = $this->options['id'];
  42.         $key           = isset($this->options['key']) ? $this->options['key'] : null;
  43.         $scriptOptions = json_encode($this->autocompleteOptions);
  44.         $view          = $this->getView();
  45.         $view->registerJsFile(self::API_URL . http_build_query([
  46.                 'libraries' => $this->libraries,
  47.                 'sensor'    => $this->sensor ? 'true' : 'false',
  48.                 'language'  => $this->language,
  49.                 'key'       => $key,
  50.             ]));
  51.         $view->registerJs(<<<JS
  52. (function(){
  53.     var input = document.getElementById('{$elementId}');
  54.     var options = {$scriptOptions};
  55.  
  56.     searchbox = new google.maps.places.Autocomplete(input, options);
  57.         setupListeners();
  58. })();
  59. JS
  60.             , \yii\web\View::POS_READY);
  61.     }
  62. }
Add Comment
Please, Sign In to add comment