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