GoogleMapV3Helper.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. <?php
  2. /**
  3. * This is a CakePHP helper that helps users to integrate google map v3
  4. * into their application by only writing php code. this helper depends on jQuery
  5. *
  6. * @author Rajib Ahmed
  7. * @version 0.10.12
  8. *
  9. * enhanced/modified by Mark Scherer
  10. */
  11. App::uses('AppHelper', 'View/Helper');
  12. /**
  13. * PHP5 / CakePHP 2.x
  14. *
  15. * @author Mark Scherer
  16. * @link http://www.dereuromark.de/2010/12/21/googlemapsv3-cakephp-helper/
  17. * @package tools plugin
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. *
  20. * fixed brackets, spacesToTabs, indends, some improvements, supports multiple maps now.
  21. * now capable of resetting itself (full or partly) for multiple maps on a single view
  22. *
  23. * CodeAPI: http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/basics.html
  24. * Icons/Images: http://gmapicons.googlepages.com/home
  25. *
  26. * v1.2: Cake2.x
  27. * 2011-10-12 ms
  28. * v1.3: E_STRICT compliant methods (url now mapUrl, link now mapLink)
  29. * 2012-08-31 ms
  30. */
  31. class GoogleMapV3Helper extends AppHelper {
  32. public static $MAP_COUNT = 0;
  33. public static $MARKER_COUNT = 0;
  34. public static $ICON_COUNT = 0;
  35. public static $INFO_WINDOW_COUNT = 0;
  36. public static $INFO_CONTENT_COUNT = 0;
  37. const API = 'maps.google.com/maps/api/js?';
  38. const STATIC_API = 'maps.google.com/maps/api/staticmap?';
  39. const TYPE_ROADMAP = 'R';
  40. const TYPE_HYBRID = 'H';
  41. const TYPE_SATELLITE = 'S';
  42. const TYPE_TERRAIN = 'T';
  43. public $types = array(
  44. self::TYPE_ROADMAP => 'ROADMAP',
  45. self::TYPE_HYBRID => 'HYBRID',
  46. self::TYPE_SATELLITE => 'SATELLITE',
  47. self::TYPE_TERRAIN => 'TERRAIN'
  48. );
  49. /**
  50. * Cakephp builtin helper
  51. *
  52. * @var array
  53. */
  54. public $helpers = array('Html', 'Js');
  55. /**
  56. * google maker config instance variable
  57. *
  58. * @var array
  59. */
  60. public $markers = array();
  61. public $infoWindows = array();
  62. public $infoContents = array();
  63. public $icons = array();
  64. public $matching = array();
  65. //public $iconMatching = array();
  66. public $map = '';
  67. protected $_mapIds = array(); # remember already used ones (valid xhtml contains ids not more than once)
  68. /**
  69. * settings of the helper
  70. * @var array
  71. */
  72. protected $_defaultOptions = array(
  73. 'zoom' =>null, # global, both map and staticMap
  74. 'lat' => null, # global, both map and staticMap
  75. 'lng' => null, # global, both map and staticMap
  76. 'type' => self::TYPE_ROADMAP,
  77. 'map'=>array(
  78. 'api' => null,
  79. 'streetViewControl' => false,
  80. 'navigationControl' => true,
  81. 'mapTypeControl' => true,
  82. 'scaleControl' => true,
  83. 'scrollwheel' => false,
  84. 'keyboardShortcuts' => true,
  85. //'zoom' =>5, # deprecated as default value, uses global one if missing
  86. //'type' =>'R', # deprecated as default value, uses global one if missing
  87. //'lat' => 51, # deprecated as default value, uses global one if missing
  88. //'lng' => 11, # deprecated as default value, uses global one if missing
  89. 'typeOptions' => array(),
  90. 'navOptions' => array(),
  91. 'scaleOptions' => array(),
  92. 'defaultLat' => 51, # only last fallback, use Configure::write('Google.lat', ...); to define own one
  93. 'defaultLng' => 11, # only last fallback, use Configure::write('Google.lng', ...); to define own one
  94. 'defaultZoom' => 5,
  95. ),
  96. 'staticMap' => array(
  97. 'size' => '300x300',
  98. //'type' =>'R', # deprecated as default value, uses global one if missing
  99. //'zoom' => 12 # deprecated as default value, uses global one if missing
  100. //'lat' => 51, # deprecated as default value, uses global one if missing
  101. //'lng' => 11, # deprecated as default value, uses global one if missing
  102. 'format' => 'png',
  103. 'mobile' => false,
  104. //'shadow' => true # for icons
  105. ),
  106. 'geolocate' => false,
  107. 'sensor' => false,
  108. 'language' => null,
  109. 'region' => null,
  110. 'showMarker' => true,
  111. //'showInfoWindow' => true,
  112. 'infoWindow' => array(
  113. 'content'=>'',
  114. 'useMultiple'=>false, # Using single infowindow object for all
  115. 'maxWidth'=>300,
  116. 'lat'=>null,
  117. 'lng'=>null,
  118. 'pixelOffset' => 0,
  119. 'zIndex' => 200,
  120. 'disableAutoPan' => false
  121. ),
  122. 'marker'=>array(
  123. //'autoCenter' => true,
  124. 'icon' => null, # => default (red marker) //http://google-maps-icons.googlecode.com/files/home.png
  125. 'title' => null,
  126. 'shadow' => null,
  127. 'shape' => null,
  128. 'zIndex' => null,
  129. 'draggable' => false,
  130. 'cursor' => null,
  131. 'directions' => false # add form with directions
  132. ),
  133. 'div'=>array(
  134. 'id'=>'map_canvas',
  135. 'width' => '100%',
  136. 'height' => '400px',
  137. 'class' => 'map',
  138. 'escape' => true
  139. ),
  140. 'event'=>array(
  141. ),
  142. 'animation' => array(
  143. //TODO
  144. ),
  145. 'callbacks' => array(
  146. 'geolocate' => null //TODO
  147. ),
  148. 'plugins' => array(
  149. 'keydragzoom' => false, # http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/
  150. 'markermanager' => false, # http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/
  151. 'markercluster' => false, # http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/
  152. ),
  153. 'autoCenter' => false, # try to fit all markers in (careful, all zooms values are omitted)
  154. 'autoScript' => false, # let the helper include the necessary js script links
  155. 'inline' => false, # for scripts
  156. 'localImages' => false,
  157. 'https' => null # auto detect
  158. );
  159. protected $_currentOptions =array();
  160. protected $_apiIncluded = false;
  161. protected $_gearsIncluded = false;
  162. protected $_located = false;
  163. public function __construct($View = null, $settings = array()) {
  164. parent::__construct($View, $settings);
  165. # read constum config settings
  166. $google = (array)Configure::read('Google');
  167. if (!empty($google['api'])) {
  168. $this->_defaultOptions['map']['api'] = $google['api'];
  169. }
  170. if (!empty($google['zoom'])) {
  171. $this->_defaultOptions['map']['zoom'] = $google['zoom'];
  172. }
  173. if (!empty($google['lat'])) {
  174. $this->_defaultOptions['map']['lat'] = $google['lat'];
  175. }
  176. if (!empty($google['lng'])) {
  177. $this->_defaultOptions['map']['lng'] = $google['lng'];
  178. }
  179. if (!empty($google['type'])) {
  180. $this->_defaultOptions['map']['type'] = $google['type'];
  181. }
  182. if (!empty($google['size'])) {
  183. $this->_defaultOptions['div']['width'] = $google['size']['width'];
  184. $this->_defaultOptions['div']['height'] = $google['size']['height'];
  185. }
  186. if (!empty($google['staticSize'])) {
  187. $this->_defaultOptions['staticMap']['size'] = $google['staticSize'];
  188. }
  189. # the following are convience defaults - if not available the map lat/lng/zoom defaults will be used
  190. if (!empty($google['staticZoom'])) {
  191. $this->_defaultOptions['staticMap']['zoom'] = $google['staticZoom'];
  192. }
  193. if (!empty($google['staticLat'])) {
  194. $this->_defaultOptions['staticMap']['lat'] = $google['staticLat'];
  195. }
  196. if (!empty($google['staticLng'])) {
  197. $this->_defaultOptions['staticMap']['lng'] = $google['staticLng'];
  198. }
  199. if (isset($google['localImages'])) {
  200. if ($google['localImages'] === true) {
  201. //$google['localImages'] = IMAGES.'google_map'.DS;
  202. $google['localImages'] = Router::url('/img/google_map/', true);
  203. }
  204. $this->_defaultOptions['localImages'] = $google['localImages'];
  205. }
  206. $this->_currentOptions = $this->_defaultOptions;
  207. }
  208. /** Google Maps JS **/
  209. /**
  210. * JS maps.google API url
  211. * Like:
  212. * http://maps.google.com/maps/api/js?sensor=true
  213. * Adds Key - more variables could be added after it with "&key=value&..."
  214. * - region
  215. * @param bool $sensor
  216. * @param string $language (iso2: en, de, ja, ...)
  217. * @param string $append (more key-value-pairs to append)
  218. * @return string $fullUrl
  219. * 2009-03-09 ms
  220. */
  221. public function apiUrl($sensor = false, $api = null, $language = null, $append = null) {
  222. $url = $this->_protocol() . self::API;
  223. $url .= 'sensor=' . ($sensor ? 'true' : 'false');
  224. if (!empty($language)) {
  225. $url .= '&language='.$language;
  226. }
  227. /*
  228. if (!empty($this->key)) {
  229. $url .= '&key='.$this->key;
  230. }
  231. */
  232. if (!empty($api)) {
  233. $this->_currentOptions['map']['api'] = $api;
  234. }
  235. if (!empty($this->_currentOptions['map']['api'])) {
  236. $url .= '&v='.$this->_currentOptions['map']['api'];
  237. }
  238. if (!empty($append)) {
  239. $url .= $append;
  240. }
  241. $this->_apiIncluded = true;
  242. return $url;
  243. }
  244. //deprecated
  245. public function gearsUrl() {
  246. $this->_gearsIncluded = true;
  247. $url = $this->_protocol() . 'code.google.com/apis/gears/gears_init.js';
  248. return $url;
  249. }
  250. /**
  251. * @return string $currentMapObject
  252. * 2010-12-18 ms
  253. */
  254. public function name() {
  255. return 'map'.self::$MAP_COUNT;
  256. }
  257. /**
  258. * @return string $currentContainerId
  259. * 2010-12-18 ms
  260. */
  261. public function id() {
  262. return $this->_currentOptions['div']['id'];
  263. }
  264. /**
  265. * make it possible to include multiple maps per page
  266. * resets markers, infoWindows etc
  267. * @param full: true=optionsAsWell
  268. * @return void
  269. * 2010-12-18 ms
  270. */
  271. public function reset($full = true) {
  272. //self::$MAP_COUNT
  273. self::$MARKER_COUNT = self::$INFO_WINDOW_COUNT = 0;
  274. $this->markers = $this->infoWindows = array();
  275. if ($full) {
  276. $this->_currentOptions = $this->_defaultOptions;
  277. }
  278. }
  279. /**
  280. * set the controls of current map
  281. * @param array $controls:
  282. * - zoom, scale, overview: TRUE/FALSE
  283. *
  284. * - map: FALSE, small, large
  285. * - type: FALSE, normal, menu, hierarchical
  286. * TIP: faster/shorter by using only the first character (e.g. "H" for "hierarchical")
  287. *
  288. * 2011-03-15 ms
  289. */
  290. public function setControls($options = array()) {
  291. if (!empty($options['streetView'])) {
  292. $this->_currentOptions['map']['streetViewControl'] = $options['streetView'];
  293. }
  294. if (!empty($options['zoom'])) {
  295. $this->_currentOptions['map']['scaleControl'] = $options['zoom'];
  296. }
  297. if (isset($options['scrollwheel'])) {
  298. $this->_currentOptions['map']['scrollwheel'] = $options['scrollwheel'];
  299. }
  300. if (isset($options['keyboardShortcuts'])) {
  301. $this->_currentOptions['map']['keyboardShortcuts'] = $options['keyboardShortcuts'];
  302. }
  303. /*
  304. if (!empty($options['map'])) {
  305. if ($options['map'] === 'l' || $options['map'] === 'large') {
  306. $this->setMapControl('GLargeMapControl()');
  307. } else {
  308. $this->setMapControl('GSmallMapControl()');
  309. }
  310. }
  311. */
  312. if (!empty($options['type'])) {
  313. /*
  314. if ($options['type'] === 'm' || $options['type'] === 'menu') {
  315. $this->setMapControl('GMenuMapTypeControl()');
  316. } elseif ($options['type'] === 'h' || $options['type'] === 'hierarchical') {
  317. $this->setMapControl('GHierarchicalMapTypeControl()');
  318. } else {
  319. $this->setMapControl('GMapTypeControl()');
  320. }
  321. */
  322. $this->_currentOptions['map']['type'] = $options['type'];
  323. }
  324. }
  325. /**
  326. * This the initialization point of the script
  327. * Returns the div container you can echo on the website
  328. *
  329. * @param array $options associative array of settings are passed
  330. * @return string $divContainer
  331. * 2010-12-20 ms
  332. */
  333. public function map($options = array()) {
  334. $this->reset();
  335. $this->_currentOptions = Set::merge($this->_currentOptions, $options);
  336. $this->_currentOptions['map'] = array_merge($this->_currentOptions['map'], array('zoom'=>$this->_currentOptions['zoom'], 'lat' => $this->_currentOptions['lat'], 'lng' => $this->_currentOptions['lng'], 'type' => $this->_currentOptions['type']), $options);
  337. if (!$this->_currentOptions['map']['lat'] || !$this->_currentOptions['map']['lng']) {
  338. $this->_currentOptions['map']['lat'] = $this->_currentOptions['map']['defaultLat'];
  339. $this->_currentOptions['map']['lng'] = $this->_currentOptions['map']['defaultLng'];
  340. $this->_currentOptions['map']['zoom'] = $this->_currentOptions['map']['defaultZoom'];
  341. } elseif (!$this->_currentOptions['map']['zoom']) {
  342. $this->_currentOptions['map']['zoom'] = $this->_currentOptions['map']['defaultZoom'];
  343. }
  344. # autoinclude js?
  345. if (!empty($options['autoScript']) && !$this->_apiIncluded) {
  346. $res = $this->Html->script($this->apiUrl(), array('inline'=>$options['inline']));
  347. if ($options['inline']) {
  348. echo $res;
  349. }
  350. # usually already included
  351. //http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
  352. }
  353. # still not very common: http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/basics.html
  354. if (false && !empty($options['autoScript']) && !$this->_gearsIncluded) {
  355. $res = $this->Html->script($this->gearsUrl(), array('inline'=>$options['inline']));
  356. if ($options['inline']) {
  357. echo $res;
  358. }
  359. }
  360. $map = "
  361. var initialLocation = ".$this->_initialLocation().";
  362. var browserSupportFlag = new Boolean();
  363. var myOptions = ".$this->_mapOptions().";
  364. // deprecated
  365. gMarkers".self::$MAP_COUNT." = new Array();
  366. gInfoWindows".self::$MAP_COUNT." = new Array();
  367. gWindowContents".self::$MAP_COUNT." = new Array();
  368. ";
  369. #rename "map_canvas" to "map_canvas1", ... if multiple maps on one page
  370. while (in_array($this->_currentOptions['div']['id'], $this->_mapIds)) {
  371. $this->_currentOptions['div']['id'] .= '-1'; //TODO: improve
  372. }
  373. $this->_mapIds[] = $this->_currentOptions['div']['id'];
  374. $map .= "
  375. var ".$this->name()." = new google.maps.Map(document.getElementById(\"".$this->_currentOptions['div']['id']."\"), myOptions);
  376. ";
  377. $this->map = $map;
  378. $result = '';
  379. $this->_currentOptions['div']['style'] = '';
  380. if (is_numeric($this->_currentOptions['div']['width'])) {
  381. $this->_currentOptions['div']['width'] .= 'px';
  382. }
  383. if (is_numeric($this->_currentOptions['div']['height'])) {
  384. $this->_currentOptions['div']['height'] .= 'px';
  385. }
  386. $this->_currentOptions['div']['style'] .= 'width: '.$this->_currentOptions['div']['width'].';';
  387. $this->_currentOptions['div']['style'] .= 'height: '.$this->_currentOptions['div']['height'].';';
  388. unset($this->_currentOptions['div']['width']); unset($this->_currentOptions['div']['height']);
  389. $defaultText = isset($this->_currentOptions['content']) ? $this->_currentOptions['content'] : __('Map cannot be displayed!');
  390. $result = $this->Html->tag('div', $defaultText, $this->_currentOptions['div']);
  391. return $result;
  392. }
  393. public function _initialLocation() {
  394. if ($this->_currentOptions['map']['lat'] && $this->_currentOptions['map']['lng']) {
  395. return "new google.maps.LatLng(".$this->_currentOptions['map']['lat'].", ".$this->_currentOptions['map']['lng'].")";
  396. }
  397. $this->_currentOptions['autoCenter'] = true;
  398. return 'false';
  399. }
  400. /**
  401. * @param array $options
  402. * - lat, lng, title, content, icon, directions
  403. * @return int $markerCount or false on failure
  404. * 2010-12-18 ms
  405. */
  406. public function addMarker($options) {
  407. if (empty($options)) {
  408. return false;
  409. }
  410. if (!isset($options['lat']) || !isset($options['lng'])) {
  411. return false;
  412. };
  413. if (!preg_match("/[-+]?\b[0-9]*\.?[0-9]+\b/", $options['lat']) || !preg_match("/[-+]?\b[0-9]*\.?[0-9]+\b/", $options['lng'])) {
  414. return false;
  415. }
  416. $defaults = $this->_currentOptions['marker'];
  417. if (isset($options['icon']) && is_array($options['icon'])) {
  418. $defaults = array_merge($defaults, $options['icon']);
  419. unset($options['icon']);
  420. }
  421. $options = array_merge($defaults, $options);
  422. $params = array();
  423. $params['map'] = $this->name();
  424. if (isset($options['title'])) {
  425. $params['title'] = json_encode($options['title']);
  426. }
  427. if (isset($options['icon'])) {
  428. $params['icon'] = $options['icon'];
  429. if (is_int($params['icon'])) {
  430. $params['icon'] = 'gIcons'.self::$MAP_COUNT.'['.$params['icon'].']';
  431. } else {
  432. $params['icon'] = json_encode($params['icon']);
  433. }
  434. }
  435. if (isset($options['shadow'])) {
  436. $params['shadow'] = $options['shadow'];
  437. if (is_int($params['shadow'])) {
  438. $params['shadow'] = 'gIcons'.self::$MAP_COUNT.'['.$params['shadow'].']';
  439. }
  440. }
  441. if (isset($options['shape'])) {
  442. $params['shape'] = $options['shape'];
  443. }
  444. if (isset($options['zIndex'])) {
  445. $params['zIndex'] = $options['zIndex'];
  446. }
  447. $marker = "
  448. var x".self::$MARKER_COUNT." = new google.maps.Marker({
  449. position: new google.maps.LatLng(".$options['lat'].",".$options['lng']."),
  450. ".$this->_toObjectParams($params, false, false)."
  451. });
  452. gMarkers".self::$MAP_COUNT.".push(
  453. x".self::$MARKER_COUNT."
  454. );
  455. ";
  456. $this->map.= $marker;
  457. if (!empty($options['directions'])) {
  458. $options['content'] .= $this->_directions($options['directions'], $options);
  459. }
  460. if (!empty($options['content']) && $this->_currentOptions['infoWindow']['useMultiple']) {
  461. $x = $this->addInfoWindow(array('content'=>$options['content']));
  462. $this->setContentInfoWindow($options['content'], $x);
  463. /*
  464. $marker .= "
  465. var window".self::$MARKER_COUNT." = new google.maps.InfoWindow({ content: '".$options['content']."',
  466. size: new google.maps.Size(50,50)
  467. });
  468. google.maps.event.addListener(x".self::$MARKER_COUNT.", 'click', function() {
  469. / ".$this->name().".setZoom(7); /
  470. infowindow.setContent(gWindows[".self::$MARKER_COUNT."]);
  471. infowindow.setPosition(event.latLng);
  472. infowindow.open(map);
  473. });
  474. ";
  475. */
  476. $this->addEvent($x);
  477. } elseif (!empty($options['content'])) {
  478. if (!isset($this->_currentOptions['marker']['infoWindow'])) {
  479. $this->_currentOptions['marker']['infoWindow'] = $this->addInfoWindow();
  480. }
  481. $x = $this->addInfoContent($options['content']);
  482. $event = "
  483. gInfoWindows".self::$MAP_COUNT."[".$this->_currentOptions['marker']['infoWindow']."].setContent(gWindowContents".self::$MAP_COUNT."[".self::$MARKER_COUNT."]);
  484. gInfoWindows".self::$MAP_COUNT."[".$this->_currentOptions['marker']['infoWindow']."].open(".$this->name().", gMarkers".self::$MAP_COUNT."[".self::$MARKER_COUNT."]);
  485. ";
  486. $this->addCustomEvent(self::$MARKER_COUNT, $event);
  487. }
  488. # custom matching event?
  489. if (isset($options['id'])) {
  490. $this->matching[$options['id']] = self::$MARKER_COUNT;
  491. }
  492. /*
  493. //$this->mapMarkers[$id] = ;
  494. //$function = 'function() { '.$id.'.'.$call.'("'.$content.'");}';
  495. $function = 'function() { mapMarkers[\''.$id.'\'].'.$call.'(mapWindows[\''.$id.'\']);}';
  496. $this->addListener($id, $function, isset($options['action'])?$options['action']:null);
  497. //"gInfoWindows".self::$MAP_COUNT.".setContent(gWindowContents1[1]);
  498. //"gInfoWindows".self::$MAP_COUNT.".open(map1, gMarkers1[1]);
  499. */
  500. return self::$MARKER_COUNT++;
  501. }
  502. /**
  503. * build directions form (type get) for directions inside infoWindows
  504. * @param mixed $directions
  505. * - bool TRUE for autoDirections (using lat/lng)
  506. * @param array $options
  507. * - options array of marker for autoDirections etc (optional)
  508. * 2011-03-22 ms
  509. */
  510. public function _directions($directions, $markerOptions = array()) {
  511. $options = array(
  512. 'from' => null,
  513. 'to' => null,
  514. 'label' => __('Enter your address'),
  515. 'submit' => __('Get directions'),
  516. 'escape' => true,
  517. 'zoom' => null, # auto
  518. );
  519. if ($directions === true) {
  520. $options['to'] = $markerOptions['lat'].','.$markerOptions['lng'];
  521. } elseif (is_array($directions)) {
  522. $options = array_merge($options, $directions);
  523. }
  524. if (empty($options['to']) && empty($options['from'])) {
  525. return '';
  526. }
  527. $form = '<form action="http://maps.google.com/maps" method="get" target="_blank">';
  528. $form .= $options['escape'] ? h($options['label']) : $options['label'];
  529. if (!empty($options['from'])) {
  530. $form .= '<input type="hidden" name="saddr" value="'.$options['from'].'" />';
  531. } else {
  532. $form .= '<input type="text" name="saddr" />';
  533. }
  534. if (!empty($options['to'])) {
  535. $form .= '<input type="hidden" name="daddr" value="'.$options['to'].'" />';
  536. } else {
  537. $form .= '<input type="text" name="daddr" />';
  538. }
  539. if (isset($options['zoom'])) {
  540. $form .= '<input type="hidden" name="z" value="'.$options['zoom'].'" />';
  541. }
  542. $form .= '<input type="submit" value="'.$options['submit'].'" />';
  543. $form .= '</form>';
  544. return '<div class="directions">'.$form.'</div>';
  545. }
  546. public function addInfoContent($con) {
  547. $this->infoContents[self::$MARKER_COUNT] = $this->escapeString($con);
  548. $event = "
  549. gWindowContents".self::$MAP_COUNT.".push(".$this->escapeString($con).");
  550. ";
  551. $this->addCustom($event);
  552. //TODO: own count?
  553. return self::$MARKER_COUNT;
  554. }
  555. public $setIcons = array(
  556. 'color' => 'http://www.google.com/mapfiles/marker%s.png',
  557. 'alpha' => 'http://www.google.com/mapfiles/marker%s%s.png',
  558. 'numeric' => 'http://google-maps-icons.googlecode.com/files/%s%s.png',
  559. 'special' => 'http://google-maps-icons.googlecode.com/files/%s.png'
  560. );
  561. /**
  562. * get a custom icon set
  563. * @param color: green, red, purple, ... or some special ones like "home", ...
  564. * @param char: A...Z or 0...20/100 (defaults to none)
  565. * @param size: s, m, l (defaults to medium)
  566. * NOTE: for special ones only first parameter counts!
  567. * @return array: array(icon, shadow, shape, ...)
  568. * 2011-03-14 ms
  569. */
  570. public function iconSet($color, $char = null, $size = 'm') {
  571. $colors = array('red', 'green', 'yellow', 'blue', 'purple', 'white', 'black');
  572. if (!in_array($color, $colors)) {
  573. $color = 'red';
  574. }
  575. if (!empty($this->_currentOptions['localImages'])) {
  576. $this->setIcons['color'] = $this->_currentOptions['localImages'].'marker%s.png';
  577. $this->setIcons['alpha'] = $this->_currentOptions['localImages'].'marker%s%s.png';
  578. $this->setIcons['numeric'] = $this->_currentOptions['localImages'].'%s%s.png';
  579. $this->setIcons['special'] = $this->_currentOptions['localImages'].'%s.png';
  580. }
  581. if (!empty($char)) {
  582. if ($color === 'red') {
  583. $color = '';
  584. } else {
  585. $color = '_'.$color;
  586. }
  587. $url = sprintf($this->setIcons['alpha'], $color, $char);
  588. } else {
  589. if ($color === 'red') {
  590. $color = '';
  591. } else {
  592. $color = '_'.$color;
  593. }
  594. $url = sprintf($this->setIcons['color'], $color);
  595. }
  596. /*
  597. var iconImage = new google.maps.MarkerImage('images/' + images[0] + '.png',
  598. new google.maps.Size(iconData[images[0]].width, iconData[images[0]].height),
  599. new google.maps.Point(0,0),
  600. new google.maps.Point(0, 32)
  601. );
  602. var iconShadow = new google.maps.MarkerImage('images/' + images[1] + '.png',
  603. new google.maps.Size(iconData[images[1]].width, iconData[images[1]].height),
  604. new google.maps.Point(0,0),
  605. new google.maps.Point(0, 32)
  606. );
  607. var iconShape = {
  608. coord: [1, 1, 1, 32, 32, 32, 32, 1],
  609. type: 'poly'
  610. };
  611. */
  612. $shadow = 'http://www.google.com/mapfiles/shadow50.png';
  613. $res = array('url'=>$url, 'icon'=>$this->icon($url, array('size'=>array('width'=>20, 'height'=>34))), 'shadow'=>$this->icon($shadow, array('size'=>array('width'=>37, 'height'=>34), 'shadow'=>array('width'=>10, 'height'=>34))));
  614. //$this->icons[$ICON_COUNT] = $res;
  615. //$ICON_COUNT++;
  616. return $res;
  617. }
  618. /**
  619. * @param string $imageUrl (http://...)
  620. * @param string $shadowImageUrl (http://...)
  621. * @param array $imageOptions
  622. * @param array $shadowImageOptions
  623. * custom icon: http://thydzik.com/thydzikGoogleMap/markerlink.php?text=?&color=FFFFFF
  624. * custom icons: http://code.google.com/p/google-maps-icons/wiki/NumericIcons#Lettered_Balloons_from_A_to_Z,_in_10_Colors
  625. * custom shadows: http://www.cycloloco.com/shadowmaker/shadowmaker.htm
  626. * 2011-03-13 ms
  627. */
  628. public function addIcon($image, $shadow = null, $imageOptions = array(), $shadowOptions = array()) {
  629. $res = array('url'=>$image);
  630. $res['icon'] = $this->icon($image, $imageOptions);
  631. if ($shadow) {
  632. $last = $this->_iconRemember[$res['icon']];
  633. if (!isset($shadowOptions['anchor'])) {
  634. $shadowOptions['anchor'] = array();
  635. }
  636. $shadowOptions['anchor'] = array_merge($shadowOptions['anchor'], $last['options']['anchor']);
  637. $res['shadow'] = $this->icon($shadow, $shadowOptions);
  638. }
  639. return $res;
  640. }
  641. protected $_iconRemember = array();
  642. /**
  643. * generate icon object
  644. * @param url (required)
  645. * @param options (optional):
  646. * - size: array(width=>x, height=>y)
  647. * - origin: array(width=>x, height=>y)
  648. * - anchor: array(width=>x, height=>y)
  649. */
  650. public function icon($url, $options = array()) {
  651. // The shadow image is larger in the horizontal dimension
  652. // while the position and offset are the same as for the main image.
  653. if (empty($options['size'])) {
  654. if ($data = @getimagesize($url)) {
  655. $options['size']['width'] = $data[0];
  656. $options['size']['height'] = $data[1];
  657. } else {
  658. $options['size']['width'] = $options['size']['height'] = 0;
  659. }
  660. }
  661. if (empty($options['anchor'])) {
  662. $options['anchor']['width'] = intval($options['size']['width']/2);
  663. $options['anchor']['height'] = $options['size']['height'];
  664. }
  665. if (empty($options['origin'])) {
  666. $options['origin']['width'] = $options['origin']['height'] = 0;
  667. }
  668. if (isset($options['shadow'])) {
  669. $options['anchor'] = $options['shadow'];
  670. }
  671. //pr(returns($options));
  672. $icon = 'new google.maps.MarkerImage(\''.$url.'\',
  673. new google.maps.Size('.$options['size']['width'].', '.$options['size']['height'].'),
  674. new google.maps.Point('.$options['origin']['width'].', '.$options['origin']['height'].'),
  675. new google.maps.Point('.$options['anchor']['width'].', '.$options['anchor']['height'].')
  676. )';
  677. $this->icons[self::$ICON_COUNT] = $icon;
  678. $this->_iconRemember[self::$ICON_COUNT] = array('url'=>$url, 'options'=>$options, 'id'=>self::$ICON_COUNT);
  679. //$this->map .= $code;
  680. return self::$ICON_COUNT++;
  681. }
  682. /**
  683. * @param array $options
  684. * - lat, lng, content, maxWidth, pixelOffset, zIndex
  685. * @return int $windowCount
  686. * 2010-12-18 ms
  687. */
  688. public function addInfoWindow($options=array()) {
  689. $options = $this->_currentOptions['infoWindow'];
  690. $options = array_merge($options, $options);
  691. if (!empty($options['lat']) && !empty($options['lng'])) {
  692. $position = "new google.maps.LatLng(".$options['lat'].", ".$options['lng'].")";
  693. } else {
  694. $position = " ".$this->name().".getCenter()";
  695. }
  696. $windows = "
  697. gInfoWindows".self::$MAP_COUNT.".push( new google.maps.InfoWindow({
  698. position: {$position},
  699. content: ".$this->escapeString($options['content']).",
  700. maxWidth: {$options['maxWidth']},
  701. pixelOffset: {$options['pixelOffset']}
  702. /*zIndex: {$options['zIndex']},*/
  703. }));
  704. ";
  705. $this->map .= $windows;
  706. return self::$INFO_WINDOW_COUNT++;
  707. }
  708. /**
  709. * @param int $marker
  710. * @param int $infoWindow
  711. * @return void
  712. * 2010-12-18 ms
  713. */
  714. public function addEvent($marker, $infoWindow) {
  715. $this->map .= "
  716. google.maps.event.addListener(gMarkers[{$marker}], 'click', function() {
  717. gInfoWindows".self::$MAP_COUNT."[$infoWindow].open(".$this->name().", this);
  718. });
  719. ";
  720. }
  721. /**
  722. * @param int $marker
  723. * @param string $event (js)
  724. * @return void
  725. * 2010-12-18 ms
  726. */
  727. public function addCustomEvent($marker, $event) {
  728. $this->map .= "
  729. google.maps.event.addListener(gMarkers".self::$MAP_COUNT."[{$marker}], 'click', function() {
  730. $event
  731. });
  732. ";
  733. }
  734. /**
  735. * @param string $custom (js)
  736. * @return void
  737. * 2010-12-18 ms
  738. */
  739. public function addCustom($js) {
  740. $this->map .= $js;
  741. }
  742. /**
  743. * @param string $content (html/text)
  744. * @param int $infoWindowCount
  745. * @return void
  746. * 2010-12-18 ms
  747. */
  748. public function setContentInfoWindow($con, $index) {
  749. $this->map .= "
  750. gInfoWindows".self::$MAP_COUNT."[$index].setContent(".$this->escapeString($con).");";
  751. }
  752. /**
  753. * json encode string
  754. *
  755. * @param mixed $content
  756. * @return json
  757. */
  758. public function escapeString($content) {
  759. return json_encode($content);
  760. }
  761. /**
  762. * This method returns the javascript for the current map container
  763. * Just echo it below the map container
  764. * @return string
  765. * 2010-12-18 ms
  766. */
  767. public function script() {
  768. $script='<script type="text/javascript">
  769. '.$this->_arrayToObject('matching', $this->matching, false, true).'
  770. '.$this->_arrayToObject('gIcons'.self::$MAP_COUNT, $this->icons, false, false).'
  771. jQuery(document).ready(function() {
  772. ';
  773. $script .= $this->map;
  774. if ($this->_currentOptions['geolocate']) {
  775. $script .= $this->_geolocate();
  776. }
  777. if ($this->_currentOptions['showMarker'] && !empty($this->markers) && is_array($this->markers)) {
  778. $script .= implode($this->markers, " ");
  779. }
  780. if ($this->_currentOptions['autoCenter']) {
  781. $script .= $this->_autoCenter();
  782. }
  783. $script .= '
  784. });
  785. </script>';
  786. self::$MAP_COUNT++;
  787. return $script;
  788. }
  789. /**
  790. * set a custom geolocate callback
  791. * @param string $customJs
  792. * false: no callback at all
  793. * @return void
  794. * 2011-03-16 ms
  795. */
  796. public function geolocateCallback($js) {
  797. if ($js === false) {
  798. $this->_currentOptions['callbacks']['geolocate'] = false;
  799. return;
  800. }
  801. $this->_currentOptions['callbacks']['geolocate'] = $js;
  802. }
  803. /**
  804. * experimental - works in cutting edge browsers like chrome10
  805. * 2011-03-16 ms
  806. */
  807. protected function _geolocate() {
  808. return '
  809. // Try W3C Geolocation (Preferred)
  810. if (navigator.geolocation) {
  811. browserSupportFlag = true;
  812. navigator.geolocation.getCurrentPosition(function(position) {
  813. geolocationCallback(position.coords.latitude, position.coords.longitude);
  814. }, function() {
  815. handleNoGeolocation(browserSupportFlag);
  816. });
  817. // Try Google Gears Geolocation
  818. } else if (google.gears) {
  819. browserSupportFlag = true;
  820. var geo = google.gears.factory.create(\'beta.geolocation\');
  821. geo.getCurrentPosition(function(position) {
  822. geolocationCallback(position.latitude, position.longitude);
  823. }, function() {
  824. handleNoGeoLocation(browserSupportFlag);
  825. });
  826. // Browser doesn\'t support Geolocation
  827. } else {
  828. browserSupportFlag = false;
  829. handleNoGeolocation(browserSupportFlag);
  830. }
  831. function geolocationCallback(lat, lng) {
  832. '.$this->_geolocationCallback().'
  833. }
  834. function handleNoGeolocation(errorFlag) {
  835. if (errorFlag == true) {
  836. //alert("Geolocation service failed.");
  837. } else {
  838. //alert("Your browser doesn\'t support geolocation. We\'ve placed you in Siberia.");
  839. }
  840. //'.$this->name().'.setCenter(initialLocation);
  841. }
  842. ';
  843. }
  844. protected function _geolocationCallback() {
  845. if (($js = $this->_currentOptions['callbacks']['geolocate']) === false) {
  846. return '';
  847. }
  848. if ($js === null) {
  849. $js = 'initialLocation = new google.maps.LatLng(lat, lng);
  850. '.$this->name().'.setCenter(initialLocation);
  851. ';
  852. }
  853. return $js;
  854. }
  855. /**
  856. * auto center map
  857. * careful: with only one marker this can result in too high zoom values!
  858. * @return string $autoCenterCommands
  859. * 2010-12-17 ms
  860. */
  861. protected function _autoCenter() {
  862. return '
  863. var bounds = new google.maps.LatLngBounds();
  864. $.each(gMarkers'.self::$MAP_COUNT.',function (index, marker) { bounds.extend(marker.position);});
  865. '.$this->name().'.fitBounds(bounds);
  866. ';
  867. }
  868. /**
  869. * @return json like js string
  870. * 2010-12-17 ms
  871. */
  872. protected function _mapOptions() {
  873. $options = array_merge($this->_currentOptions, $this->_currentOptions['map']);
  874. $mapOptions = array_intersect_key($options, array(
  875. 'streetViewControl' => null,
  876. 'navigationControl' => null,
  877. 'mapTypeControl' => null,
  878. 'scaleControl' => null,
  879. 'scrollwheel' => null,
  880. 'zoom' => null,
  881. 'keyboardShortcuts' => null
  882. ));
  883. $res = array();
  884. foreach ($mapOptions as $key => $mapOption) {
  885. $res[] = $key.': '.$this->Js->value($mapOption);
  886. }
  887. if (empty($options['autoCenter'])) {
  888. $res[] = 'center: initialLocation';
  889. }
  890. if (!empty($options['navOptions'])) {
  891. $res[] = 'navigationControlOptions: '.$this->_controlOptions('nav', $options['navOptions']);
  892. }
  893. if (!empty($options['typeOptions'])) {
  894. $res[] = 'mapTypeControlOptions: '.$this->_controlOptions('type', $options['typeOptions']);
  895. }
  896. if (!empty($options['scaleOptions'])) {
  897. $res[] = 'scaleControlOptions: '.$this->_controlOptions('scale', $options['scaleOptions']);
  898. }
  899. if (array_key_exists($options['type'], $this->types)) {
  900. $type = $this->types[$options['type']];
  901. } else {
  902. $type = $options['type'];
  903. }
  904. $res[] = 'mapTypeId: google.maps.MapTypeId.'.$type;
  905. return '{'.implode(', ', $res).'}';
  906. }
  907. /**
  908. * @return json like js string
  909. * 2010-12-17 ms
  910. */
  911. protected function _controlOptions($type, $options) {
  912. $mapping = array(
  913. 'nav' => 'NavigationControlStyle',
  914. 'type' => 'MapTypeControlStyle',
  915. 'scale' => ''
  916. );
  917. $res = array();
  918. if (!empty($options['style']) && ($m = $mapping[$type])) {
  919. $res[] = 'style: google.maps.'.$m.'.'.$options['style'];
  920. }
  921. if (!empty($options['pos'])) {
  922. $res[] = 'position: google.maps.ControlPosition.'.$options['pos'];
  923. }
  924. return '{'.implode(', ', $res).'}';
  925. }
  926. /** Google Maps Link **/
  927. /**
  928. * returns a maps.google link
  929. *
  930. * @param string $linkTitle
  931. * @param array $mapOptions
  932. * @param array $linkOptions
  933. * @return string Html link
  934. * 2011-03-12 ms
  935. */
  936. public function mapLink($title, $mapOptions = array(), $linkOptions = array()) {
  937. return $this->Html->link($title, $this->mapUrl($mapOptions), $linkOptions);
  938. }
  939. /**
  940. * returns a maps.google url
  941. *
  942. * @param array options:
  943. * - from: necessary (address or lat,lng)
  944. * - to: 1x necessary (address or lat,lng - can be an array of multiple destinations: array('dest1', 'dest2'))
  945. * - zoom: optional (defaults to none)
  946. * @return string link: http://...
  947. * 2010-12-18 ms
  948. */
  949. public function mapUrl($options = array()) {
  950. $url = $this->_protocol() . 'maps.google.com/maps?';
  951. $urlArray = array();
  952. if (!empty($options['from'])) {
  953. $urlArray[] = 'saddr=' . urlencode($options['from']);
  954. }
  955. if (!empty($options['to']) && is_array($options['to'])) {
  956. $to = array_shift($options['to']);
  957. foreach ($options['to'] as $key => $value) {
  958. $to .= '+to:' . $value;
  959. }
  960. $urlArray[] = 'daddr=' . urlencode($to);
  961. } elseif (!empty($options['to'])) {
  962. $urlArray[] = 'daddr=' . urlencode($options['to']);
  963. }
  964. if (!empty($options['zoom'])) {
  965. $urlArray[] = 'z=' . (int)$options['zoom'];
  966. }
  967. //$urlArray[] = 'f=d';
  968. //$urlArray[] = 'hl=de';
  969. //$urlArray[] = 'ie=UTF8';
  970. return $url . (implode('&', $urlArray));
  971. }
  972. /** STATIC MAP **/
  973. /** http://maps.google.com/staticmap?center=40.714728,-73.998672&zoom=14&size=512x512&maptype=mobile&markers=40.702147,-74.015794,blues%7C40.711614,-74.012318,greeng%7C40.718217,-73.998284,redc&mobile=true&sensor=false **/
  974. /**
  975. * Create a plain image map
  976. * @link http://code.google.com/intl/de-DE/apis/maps/documentation/staticmaps
  977. * @param options:
  978. * - string $size [necessary: VALxVAL, e.g. 500x400 - max 640x640]
  979. * - string $center: x,y or address [necessary, if no markers are given; else tries to take defaults if available] or TRUE/FALSE
  980. * - int $zoom [optional; if no markers are given, default value is used; if set to "auto" and ]*
  981. * - array $markers [optional, @see staticPaths() method]
  982. * - string $type [optional: roadmap/hybrid, ...; default:roadmap]
  983. * - string $mobile TRUE/FALSE
  984. * - string $visible: $area (x|y|...)
  985. * - array $paths [optional, @see staticPaths() method]
  986. * - string $language [optional]
  987. * @param array $attributes: html attributes for the image
  988. * - title
  989. * - alt (defaults to 'Map')
  990. * - url (tip: you can pass $this->link(...) and it will create a link to maps.google.com)
  991. * @return string $imageTag
  992. * 2010-12-18 ms
  993. */
  994. public function staticMap($options = array(), $attributes = array()) {
  995. $defaultAttributes = array('alt' => __('Map'));
  996. return $this->Html->image($this->staticMapUrl($options), array_merge($defaultAttributes, $attributes));
  997. }
  998. /**
  999. * Create a link to a plain image map
  1000. * @param string $linkTitle
  1001. * @param array $mapOptions
  1002. * @param array $linkOptions
  1003. * @return string Html link
  1004. * 2011-03-12 ms
  1005. */
  1006. public function staticMapLink($title, $mapOptions = array(), $linkOptions = array()) {
  1007. return $this->Html->link($title, $this->staticMapUrl($mapOptions), $linkOptions);
  1008. }
  1009. /**
  1010. * Create an url to a plain image map
  1011. * @param options
  1012. * - see staticMap() for details
  1013. * @return string $urlOfImage: http://...
  1014. * 2010-12-18 ms
  1015. */
  1016. public function staticMapUrl($options = array()) {
  1017. $map = $this->_protocol() . self::STATIC_API;
  1018. /*
  1019. $params = array(
  1020. 'sensor' => 'false',
  1021. 'mobile' => 'false',
  1022. 'format' => 'png',
  1023. //'center' => false
  1024. );
  1025. if (!empty($options['sensor'])) {
  1026. $params['sensor'] = 'true';
  1027. }
  1028. if (!empty($options['mobile'])) {
  1029. $params['mobile'] = 'true';
  1030. }
  1031. */
  1032. $defaults = array_merge($this->_defaultOptions, $this->_defaultOptions['staticMap']);
  1033. $mapOptions = array_merge($defaults, $options);
  1034. $params = array_intersect_key($mapOptions, array(
  1035. 'sensor' => null,
  1036. 'mobile' => null,
  1037. 'format' => null,
  1038. 'size' => null,
  1039. //'zoom' => null,
  1040. //'lat' => null,
  1041. //'lng' => null,
  1042. //'visible' => null,
  1043. //'type' => null,
  1044. ));
  1045. # do we want zoom to auto-correct itself?
  1046. if (!isset($options['zoom']) && !empty($mapOptions['markers'])|| !empty($mapOptions['paths']) || !empty($mapOptions['visible'])) {
  1047. $options['zoom'] = 'auto';
  1048. }
  1049. # a position on the map that is supposed to stay visible at all cost
  1050. if (!empty($mapOptions['visible'])) {
  1051. $params['visible'] = urlencode($mapOptions['visible']);
  1052. }
  1053. # center and zoom are not necccessary if path, visible or markers are given
  1054. if (!isset($options['center']) || $options['center'] === false) {
  1055. # dont use it
  1056. } elseif ($options['center'] === true && $mapOptions['lat'] !== null && $mapOptions['lng'] !== null) {
  1057. $params['center'] = urlencode((string)$mapOptions['lat'] . ',' . (string)$mapOptions['lng']);
  1058. } elseif (!empty($options['center'])) {
  1059. $params['center'] = urlencode($options['center']);
  1060. } /*else {
  1061. # try to read from markers array???
  1062. if (isset($options['markers']) && count($options['markers']) == 1) {
  1063. //pr ($options['markers']);
  1064. }
  1065. }*/
  1066. if (!isset($options['zoom']) || $options['zoom'] === false) {
  1067. # dont use it
  1068. } else {
  1069. if ($options['zoom'] === 'auto') {
  1070. if (!empty($options['markers']) && strpos($options['zoom'],'|') !== false) {
  1071. # let google find the best zoom value itself
  1072. } else {
  1073. # do something here?
  1074. }
  1075. } else {
  1076. $params['zoom'] = $options['zoom'];
  1077. }
  1078. }
  1079. if (array_key_exists($mapOptions['type'], $this->types)) {
  1080. $params['maptype'] = $this->types[$mapOptions['type']];
  1081. } else {
  1082. $params['maptype'] = $mapOptions['type'];
  1083. }
  1084. //unset($options['type']);
  1085. $params['maptype'] = strtolower($params['maptype']);
  1086. # old: {latitude},{longitude},{color}{alpha-character}
  1087. # new: @see staticMarkers()
  1088. if (!empty($options['markers'])) {
  1089. $params['markers'] = $options['markers'];
  1090. }
  1091. if (!empty($options['paths'])) {
  1092. $params['path'] = $options['paths'];
  1093. }
  1094. # valXval
  1095. if (!empty($options['size'])) {
  1096. $params['size'] = $options['size'];
  1097. }
  1098. $pieces = array();
  1099. foreach ($params as $key => $value) {
  1100. if (is_array($value)) {
  1101. $value = implode('&'.$key.'=', $value);
  1102. } elseif ($value === true) {
  1103. $value = 'true';
  1104. } elseif ($value === false) {
  1105. $value = 'false';
  1106. } elseif ($value === null) {
  1107. continue;
  1108. }
  1109. $pieces[] = $key.'='.$value;
  1110. //$map .= $key.'='.$value.'&';
  1111. }
  1112. return $map . (implode('&', $pieces));
  1113. }
  1114. /**
  1115. * prepare paths for staticMap
  1116. * @param array $pathElementArrays
  1117. * - elements: [required] (multiple array(lat=>x, lng=>y) or just a address strings)
  1118. * - color: red/blue/green (optional, default blue)
  1119. * - weight: numeric (optional, default: 5)
  1120. * @return string $paths: e.g: color:0x0000FF80|weight:5|37.40303,-122.08334|37.39471,-122.07201|37.40589,-122.06171{|...}
  1121. * 2010-12-18 ms
  1122. */
  1123. public function staticPaths($pos = array()) {
  1124. $defaults = array(
  1125. 'color' => 'blue',
  1126. 'weight' => 5 # pixel
  1127. );
  1128. # not a 2-level array? make it one
  1129. if (!isset($pos[0])) {
  1130. $pos = array($pos);
  1131. }
  1132. $res = array();
  1133. foreach ($pos as $p) {
  1134. $options = array_merge($defaults, $p);
  1135. $markers = $options['path'];
  1136. unset($options['path']);
  1137. # prepare color
  1138. if (!empty($options['color'])) {
  1139. $options['color'] = $this->_prepColor($options['color']);
  1140. }
  1141. $path = array();
  1142. foreach ($options as $key => $value) {
  1143. $path[] = $key.':'.urlencode($value);
  1144. }
  1145. foreach ($markers as $key => $pos) {
  1146. if (is_array($pos)) {
  1147. # lat/lng?
  1148. $pos = $pos['lat'].','.$pos['lng'];
  1149. }
  1150. $path[] = $pos;
  1151. }
  1152. $res[] = implode('|', $path);
  1153. }
  1154. return $res;
  1155. }
  1156. /**
  1157. * prepare markers for staticMap
  1158. * @param array $markerArrays
  1159. * - lat: xx.xxxxxx (necessary)
  1160. * - lng: xx.xxxxxx (necessary)
  1161. * - address: (instead of lat/lng)
  1162. * - color: red/blue/green (optional, default blue)
  1163. * - label: a-z or numbers (optional, default: s)
  1164. * - icon: custom icon (png, gif, jpg - max 64x64 - max 5 different icons per image)
  1165. * - shadow: TRUE/FALSE
  1166. * @param style (global) (overridden by custom marker styles)
  1167. * - color
  1168. * - label
  1169. * - icon
  1170. * - shadow
  1171. * @return array $markers: color:green|label:Z|48,11|Berlin
  1172. *
  1173. * NEW: size:mid|color:red|label:E|37.400465,-122.073003|37.437328,-122.159928&markers=size:small|color:blue|37.369110,-122.096034
  1174. * OLD: 40.702147,-74.015794,blueS|40.711614,-74.012318,greenG{|...}
  1175. * 2010-12-18 ms
  1176. */
  1177. public function staticMarkers($pos = array(), $style = array()) {
  1178. $markers = array();
  1179. $verbose = false;
  1180. $defaults = array(
  1181. 'shadow' => 'true',
  1182. 'color' => 'blue',
  1183. 'label' => '',
  1184. 'address' => '',
  1185. 'size' => ''
  1186. );
  1187. # not a 2-level array? make it one
  1188. if (!isset($pos[0])) {
  1189. $pos = array($pos);
  1190. }
  1191. # new in statitV2: separate styles! right now just merged
  1192. foreach ($pos as $p) {
  1193. $p = array_merge($defaults, $style, $p);
  1194. # adress or lat/lng?
  1195. if (!empty($p['lat']) && !empty($p['lng'])) {
  1196. $p['address'] = $p['lat'].','.$p['lng'];
  1197. } else {
  1198. $p['address'] = $p['address'];
  1199. }
  1200. $p['address'] = urlencode($p['address']);
  1201. $values = array();
  1202. # prepare color
  1203. if (!empty($p['color'])) {
  1204. $p['color'] = $this->_prepColor($p['color']);
  1205. $values[] = 'color:'.$p['color'];
  1206. }
  1207. # label? A-Z0-9
  1208. if (!empty($p['label'])) {
  1209. $values[] = 'label:'.strtoupper($p['label']);
  1210. }
  1211. if (!empty($p['size'])) {
  1212. $values[] = 'size:'.$p['size'];
  1213. }
  1214. if (!empty($p['shadow'])) {
  1215. $values[] = 'shadow:'.$p['shadow'];
  1216. }
  1217. if (!empty($p['icon'])) {
  1218. $values[] = 'icon:'.urlencode($p['icon']);
  1219. }
  1220. $values[] = $p['address'];
  1221. //TODO: icons
  1222. $markers[] = implode('|', $values);
  1223. }
  1224. //TODO: shortcut? only possible if no custom params!
  1225. if ($verbose) {
  1226. }
  1227. // long: markers=styles1|address1&markers=styles2|address2&...
  1228. // short: markers=styles,address1|address2|address3|...
  1229. return $markers;
  1230. }
  1231. /**
  1232. * Ensure that we stay on the appropriate protocol
  1233. *
  1234. * @return string protocol base (including ://)
  1235. */
  1236. protected function _protocol() {
  1237. if (($https = $this->_currentOptions['https']) === null) {
  1238. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
  1239. }
  1240. return ($https ? 'https' : 'http') . '://';
  1241. }
  1242. /**
  1243. * # to 0x
  1244. * or # added
  1245. * @param string $color: FFFFFF, #FFFFFF, 0xFFFFFF or blue
  1246. * @return string $color
  1247. * 2010-12-20 ms
  1248. */
  1249. protected function _prepColor($color) {
  1250. if (strpos($color, '#') !== false) {
  1251. return str_replace('#', '0x', $color);
  1252. } elseif (is_numeric($color)) {
  1253. return '0x'.$color;
  1254. }
  1255. return $color;
  1256. }
  1257. /** TODOS/EXP **/
  1258. /*
  1259. TODOS:
  1260. - animations
  1261. marker.setAnimation(google.maps.Animation.BOUNCE);
  1262. - geocoding (+ reverse)
  1263. - directions
  1264. - overlays
  1265. - fluster (for clustering?)
  1266. or
  1267. - markerManager (many markers)
  1268. - infoBox
  1269. http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/
  1270. - ...
  1271. */
  1272. public function geocoder() {
  1273. $js = 'var geocoder = new google.maps.Geocoder();';
  1274. //TODO
  1275. }
  1276. /**
  1277. * managing lots of markers!
  1278. * @link http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/docs/examples.html
  1279. * @param options
  1280. * -
  1281. * @return void
  1282. * 2010-12-18 ms
  1283. */
  1284. public function setManager() {
  1285. $js .= '
  1286. var mgr'.self::$MAP_COUNT.' = new MarkerManager('.$this->name().');
  1287. ';
  1288. }
  1289. public function addManagerMarker($marker, $options) {
  1290. $js = 'mgr'.self::$MAP_COUNT.'.addMarker('.$marker.');';
  1291. }
  1292. /**
  1293. * clustering for lots of markers!
  1294. * @link ?
  1295. * @param options
  1296. * -
  1297. * based on Fluster2 0.1.1
  1298. * @return void
  1299. */
  1300. public function setCluster($options) {
  1301. $js = self::$flusterScript;
  1302. $js .= '
  1303. var fluster'.self::$MAP_COUNT.' = new Fluster2('.$this->name().');
  1304. ';
  1305. # styles
  1306. 'fluster'.self::$MAP_COUNT.'.styles = {}';
  1307. $this->map .= $js;
  1308. }
  1309. public function addClusterMarker($marker, $options) {
  1310. $js = 'fluster'.self::$MAP_COUNT.'.addMarker('.$marker.');';
  1311. }
  1312. public function initCluster() {
  1313. $this->map .= 'fluster'.self::$MAP_COUNT.'.initialize();';
  1314. }
  1315. public static $flusterScript = '
  1316. function Fluster2(_map,_debug) {var map=_map;var projection=new Fluster2ProjectionOverlay(map);var me=this;var clusters=new Object();var markersLeft=new Object();this.debugEnabled=_debug;this.gridSize=60;this.markers=new Array();this.currentZoomLevel=-1;this.styles={0:{image:\'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m1.png\',textColor:\'#FFFFFF\',width:53,height:52},10:{image:\'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m2.png\',textColor:\'#FFFFFF\',width:56,height:55},20:{image:\'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m3.png\',textColor:\'#FFFFFF\',width:66,height:65}};var zoomChangedTimeout=null;function createClusters() {var zoom=map.getZoom();if (clusters[zoom]) {me.debug(\'Clusters for zoom level \'+zoom+\' already initialized.\')} else {var clustersThisZoomLevel=new Array();var clusterCount=0;var markerCount=me.markers.length;for (var i=0;i<markerCount;i++) {var marker=me.markers[i];var markerPosition=marker.getPosition();var done=false;for (var j=clusterCount-1;j>=0;j--) {var cluster=clustersThisZoomLevel[j];if (cluster.contains(markerPosition)) {cluster.addMarker(marker);done=true;break}}if (!done) {var cluster=new Fluster2Cluster(me,marker);clustersThisZoomLevel.push(cluster);clusterCount++}}clusters[zoom]=clustersThisZoomLevel;me.debug(\'Initialized \'+clusters[zoom].length+\' clusters for zoom level \'+zoom+\'.\')}if (clusters[me.currentZoomLevel]) {for (var i=0;i<clusters[me.currentZoomLevel].length;i++) {clusters[me.currentZoomLevel][i].hide()}}me.currentZoomLevel=zoom;showClustersInBounds()}function showClustersInBounds() {var mapBounds=map.getBounds();for (var i=0;i<clusters[me.currentZoomLevel].length;i++) {var cluster=clusters[me.currentZoomLevel][i];if (mapBounds.contains(cluster.getPosition())) {cluster.show()}}}this.zoomChanged=function() {window.clearInterval(zoomChangedTimeout);zoomChangedTimeout=window.setTimeout(createClusters,500)};this.getMap=function() {return map};this.getProjection=function() {return projection.getP()};this.debug=function(message) {if (me.debugEnabled) {console.log(\'Fluster2: \'+message)}};this.addMarker=function(_marker) {me.markers.push(_marker)};this.getStyles=function() {return me.styles};this.initialize=function() {google.maps.event.addListener(map,\'zoom_changed\',this.zoomChanged);google.maps.event.addListener(map,\'dragend\',showClustersInBounds);window.setTimeout(createClusters,1000)}}
  1317. function Fluster2Cluster(_fluster,_marker) {var markerPosition=_marker.getPosition();this.fluster=_fluster;this.markers=[];this.bounds=null;this.marker=null;this.lngSum=0;this.latSum=0;this.center=markerPosition;this.map=this.fluster.getMap();var me=this;var projection=_fluster.getProjection();var gridSize=_fluster.gridSize;var position=projection.fromLatLngToDivPixel(markerPosition);var positionSW=new google.maps.Point(position.x-gridSize,position.y+gridSize);var positionNE=new google.maps.Point(position.x+gridSize,position.y-gridSize);this.bounds=new google.maps.LatLngBounds(projection.fromDivPixelToLatLng(positionSW),projection.fromDivPixelToLatLng(positionNE));this.addMarker=function(_marker) {this.markers.push(_marker)};this.show=function() {if (this.markers.length==1) {this.markers[0].setMap(me.map)}else if (this.markers.length>1) {for (var i=0;i<this.markers.length;i++) {this.markers[i].setMap(null)}if (this.marker==null) {this.marker=new Fluster2ClusterMarker(this.fluster,this);if (this.fluster.debugEnabled) {google.maps.event.addListener(this.marker,\'mouseover\',me.debugShowMarkers);google.maps.event.addListener(this.marker,\'mouseout\',me.debugHideMarkers)}}this.marker.show()}};this.hide=function() {if (this.marker!=null) {this.marker.hide()}};this.debugShowMarkers=function() {for (var i=0;i<me.markers.length;i++) {me.markers[i].setVisible(true)}};this.debugHideMarkers=function() {for (var i=0;i<me.markers.length;i++) {me.markers[i].setVisible(false)}};this.getMarkerCount=function() {return this.markers.length};this.contains=function(_position) {return me.bounds.contains(_position)};this.getPosition=function() {return this.center};this.getBounds=function() {return this.bounds};this.getMarkerBounds=function() {var bounds=new google.maps.LatLngBounds(me.markers[0].getPosition(),me.markers[0].getPosition());for (var i=1;i<me.markers.length;i++) {bounds.extend(me.markers[i].getPosition())}return bounds};this.addMarker(_marker)}
  1318. function Fluster2ClusterMarker(_fluster,_cluster) {this.fluster=_fluster;this.cluster=_cluster;this.position=this.cluster.getPosition();this.markerCount=this.cluster.getMarkerCount();this.map=this.fluster.getMap();this.style=null;this.div=null;var styles=this.fluster.getStyles();for (var i in styles) {if (this.markerCount>i) {this.style=styles[i]} else {break}}google.maps.OverlayView.call(this);this.setMap(this.map);this.draw()};Fluster2ClusterMarker.prototype=new google.maps.OverlayView();Fluster2ClusterMarker.prototype.draw=function() {if (this.div==null) {var me=this;this.div=document.createElement(\'div\');this.div.style.position=\'absolute\';this.div.style.width=this.style.width+\'px\';this.div.style.height=this.style.height+\'px\';this.div.style.lineHeight=this.style.height+\'px\';this.div.style.background=\'transparent url("\'+this.style.image+\'") 50% 50% no-repeat\';this.div.style.color=this.style.textColor;this.div.style.textAlign=\'center\';this.div.style.fontFamily=\'Arial, Helvetica\';this.div.style.fontSize=\'11px\';this.div.style.fontWeight=\'bold\';this.div.innerHTML=this.markerCount;this.div.style.cursor=\'pointer\';google.maps.event.addDomListener(this.div,\'click\',function() {me.map.fitBounds(me.cluster.getMarkerBounds())});this.getPanes().overlayLayer.appendChild(this.div)}var position=this.getProjection().fromLatLngToDivPixel(this.position);this.div.style.left=(position.x-parseInt(this.style.width/2))+\'px\';this.div.style.top=(position.y-parseInt(this.style.height/2))+\'px\'};Fluster2ClusterMarker.prototype.hide=function() {this.div.style.display=\'none\'};Fluster2ClusterMarker.prototype.show=function() {this.div.style.display=\'block\'};
  1319. function Fluster2ProjectionOverlay(map) {google.maps.OverlayView.call(this);this.setMap(map);this.getP=function() {return this.getProjection()}}Fluster2ProjectionOverlay.prototype=new google.maps.OverlayView();Fluster2ProjectionOverlay.prototype.draw=function() {};
  1320. \'';
  1321. /** CALCULATING STUFF **/
  1322. /**
  1323. * Calculates Distance between two points array('lat'=>x,'lng'=>y)
  1324. * DB:
  1325. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  1326. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  1327. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  1328. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  1329. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  1330. 'AS distance'
  1331. * @param array pointX
  1332. * @param array pointY
  1333. * @return int distance: in km
  1334. * DEPRECATED - use GeocodeLib::distance() instead!
  1335. * 2009-03-06 ms
  1336. */
  1337. public function distance($pointX, $pointY) {
  1338. /*
  1339. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  1340. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  1341. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  1342. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  1343. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  1344. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  1345. */
  1346. # seems to be the only working one (although slightly incorrect...)
  1347. $res = 69.09 * rad2deg(acos(sin(deg2rad($pointX['lat'])) * sin(deg2rad($pointY['lat'])) + cos(deg2rad($pointX['lat'])) * cos(deg2rad($pointY['lat'])) * cos(deg2rad($pointX['lng'] - $pointY['lng']))));
  1348. # Miles to KM
  1349. $res *= 1.609344;
  1350. return ceil($res);
  1351. }
  1352. protected function _arrayToObject($name, $array, $asString = true, $keyAsString = false) {
  1353. $res = 'var '.$name.' = {'.PHP_EOL;
  1354. $res .= $this->_toObjectParams($array, $asString, $keyAsString);
  1355. $res .= '};';
  1356. return $res;
  1357. }
  1358. protected function _toObjectParams($array, $asString = true, $keyAsString = false) {
  1359. $pieces = array();
  1360. foreach ($array as $key => $value) {
  1361. $e = ($asString && strpos($value, 'new ') !== 0 ? '\'' : '');
  1362. $ke = ($keyAsString ? '\'' : '');
  1363. $pieces[] = $ke.$key.$ke.': '.$e.$value.$e;
  1364. }
  1365. return implode(','.PHP_EOL, $pieces);
  1366. }
  1367. }