GoogleMapV3Helper.php 57 KB

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