CGoogleApi.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * CGoogleApi class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CGoogleApi provides helper methods to easily access the {@link https://developers.google.com/loader/ Google API loader}.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @package system.web.helpers
  15. */
  16. class CGoogleApi
  17. {
  18. /**
  19. * @var string Protocol relative url to the Google API loader which allows easy access
  20. * to most of the Google AJAX APIs
  21. */
  22. public static $bootstrapUrl='//www.google.com/jsapi';
  23. /**
  24. * Renders the jsapi script file.
  25. * @param string $apiKey the API key. Null if you do not have a key.
  26. * @return string the script tag that loads Google jsapi.
  27. */
  28. public static function init($apiKey=null)
  29. {
  30. if($apiKey===null)
  31. return CHtml::scriptFile(self::$bootstrapUrl);
  32. else
  33. return CHtml::scriptFile(self::$bootstrapUrl.'?key='.$apiKey);
  34. }
  35. /**
  36. * Loads the specified API module.
  37. * Note that you should call {@link init} first.
  38. * @param string $name the module name
  39. * @param string $version the module version
  40. * @param array $options additional js options that are to be passed to the load() function.
  41. * @return string the js code for loading the module. You can use {@link CHtml::script()}
  42. * to enclose it in a script tag.
  43. */
  44. public static function load($name,$version='1',$options=array())
  45. {
  46. if(empty($options))
  47. return "google.load(\"{$name}\",\"{$version}\");";
  48. else
  49. return "google.load(\"{$name}\",\"{$version}\",".CJavaScript::encode($options).");";
  50. }
  51. /**
  52. * Registers the specified API module.
  53. * This is similar to {@link load} except that it registers the loading code
  54. * with {@link CClientScript} instead of returning it.
  55. * This method also registers the jsapi script needed by the loading call.
  56. * @param string $name the module name
  57. * @param string $version the module version
  58. * @param array $options additional js options that are to be passed to the load() function.
  59. * @param string $apiKey the API key. Null if you do not have a key.
  60. */
  61. public static function register($name,$version='1',$options=array(),$apiKey=null)
  62. {
  63. $cs=Yii::app()->getClientScript();
  64. $url=$apiKey===null?self::$bootstrapUrl:self::$bootstrapUrl.'?key='.$apiKey;
  65. $cs->registerScriptFile($url,CClientScript::POS_HEAD);
  66. $js=self::load($name,$version,$options);
  67. $cs->registerScript($name,$js,CClientScript::POS_HEAD);
  68. }
  69. }