GoogleMapV3Helper.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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 `$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. }
  458. }
  459. if (isset($options['shape'])) {
  460. $params['shape'] = $options['shape'];
  461. }
  462. if (isset($options['zIndex'])) {
  463. $params['zIndex'] = $options['zIndex'];
  464. }
  465. // geocode if necessary
  466. if (!isset($options['lat']) || !isset($options['lng'])) {
  467. $this->map.= "
  468. var geocoder = new google.maps.Geocoder();
  469. function geocodeAddress(address) {
  470. geocoder.geocode({'address': address}, function(results, status) {
  471. if (status == google.maps.GeocoderStatus.OK) {
  472. x".self::$MARKER_COUNT." = new google.maps.Marker({
  473. position: results[0].geometry.location,
  474. ".$this->_toObjectParams($params, false, false)."
  475. });
  476. gMarkers".self::$MAP_COUNT.".push(
  477. x".self::$MARKER_COUNT."
  478. );
  479. return results[0].geometry.location;
  480. } else {
  481. //alert('Geocoding was not successful for the following reason: ' + status);
  482. return null;
  483. }
  484. });
  485. }";
  486. if (!isset($options['address'])) {
  487. throw new CakeException('Either use lat/lng or address to add a marker');
  488. }
  489. $position = 'geocodeAddress(\''.h($options['address']).'\')';
  490. } else {
  491. $position = "new google.maps.LatLng(".$options['lat'].",".$options['lng'].")";
  492. }
  493. $marker = "
  494. var x".self::$MARKER_COUNT." = new google.maps.Marker({
  495. position: ".$position.",
  496. ".$this->_toObjectParams($params, false, false)."
  497. });
  498. gMarkers".self::$MAP_COUNT.".push(
  499. x".self::$MARKER_COUNT."
  500. );
  501. ";
  502. $this->map.= $marker;
  503. if (!empty($options['directions'])) {
  504. $options['content'] .= $this->_directions($options['directions'], $options);
  505. }
  506. // fill popup windows
  507. if (!empty($options['content']) && $this->_currentOptions['infoWindow']['useMultiple']) {
  508. $x = $this->addInfoWindow(array('content'=>$options['content']));
  509. $this->setContentInfoWindow($options['content'], $x);
  510. $this->addEvent($x);
  511. } elseif (!empty($options['content'])) {
  512. if (!isset($this->_currentOptions['marker']['infoWindow'])) {
  513. $this->_currentOptions['marker']['infoWindow'] = $this->addInfoWindow();
  514. }
  515. $x = $this->addInfoContent($options['content']);
  516. $event = "
  517. gInfoWindows".self::$MAP_COUNT."[".$this->_currentOptions['marker']['infoWindow']."].setContent(gWindowContents".self::$MAP_COUNT."[".$x."]);
  518. gInfoWindows".self::$MAP_COUNT."[".$this->_currentOptions['marker']['infoWindow']."].open(".$this->name().", gMarkers".self::$MAP_COUNT."[".$x."]);
  519. ";
  520. $this->addCustomEvent(self::$MARKER_COUNT, $event);
  521. }
  522. // custom matching event?
  523. if (isset($options['id'])) {
  524. $this->matching[$options['id']] = self::$MARKER_COUNT;
  525. }
  526. return self::$MARKER_COUNT++;
  527. }
  528. /**
  529. * Build directions form (type get) for directions inside infoWindows
  530. *
  531. * @param mixed $directions
  532. * - bool TRUE for autoDirections (using lat/lng)
  533. * @param array $options
  534. * - options array of marker for autoDirections etc (optional)
  535. * @return HTML
  536. * 2011-03-22 ms
  537. */
  538. public function _directions($directions, $markerOptions = array()) {
  539. $options = array(
  540. 'from' => null,
  541. 'to' => null,
  542. 'label' => __('Enter your address'),
  543. 'submit' => __('Get directions'),
  544. 'escape' => true,
  545. 'zoom' => null, # auto
  546. );
  547. if ($directions === true) {
  548. $options['to'] = $markerOptions['lat'].','.$markerOptions['lng'];
  549. } elseif (is_array($directions)) {
  550. $options = array_merge($options, $directions);
  551. }
  552. if (empty($options['to']) && empty($options['from'])) {
  553. return '';
  554. }
  555. $form = '<form action="http://maps.google.com/maps" method="get" target="_blank">';
  556. $form .= $options['escape'] ? h($options['label']) : $options['label'];
  557. if (!empty($options['from'])) {
  558. $form .= '<input type="hidden" name="saddr" value="'.$options['from'].'" />';
  559. } else {
  560. $form .= '<input type="text" name="saddr" />';
  561. }
  562. if (!empty($options['to'])) {
  563. $form .= '<input type="hidden" name="daddr" value="'.$options['to'].'" />';
  564. } else {
  565. $form .= '<input type="text" name="daddr" />';
  566. }
  567. if (isset($options['zoom'])) {
  568. $form .= '<input type="hidden" name="z" value="'.$options['zoom'].'" />';
  569. }
  570. $form .= '<input type="submit" value="'.$options['submit'].'" />';
  571. $form .= '</form>';
  572. return '<div class="directions">'.$form.'</div>';
  573. }
  574. /**
  575. * @return int Current Marker counter
  576. */
  577. public function addInfoContent($con) {
  578. $this->infoContents[self::$MARKER_COUNT] = $this->escapeString($con);
  579. $event = "
  580. gWindowContents".self::$MAP_COUNT.".push(".$this->escapeString($con).");
  581. ";
  582. $this->addCustom($event);
  583. //TODO: own count?
  584. return self::$MARKER_COUNT;
  585. }
  586. public $setIcons = array(
  587. 'color' => 'http://www.google.com/mapfiles/marker%s.png',
  588. 'alpha' => 'http://www.google.com/mapfiles/marker%s%s.png',
  589. 'numeric' => 'http://google-maps-icons.googlecode.com/files/%s%s.png',
  590. 'special' => 'http://google-maps-icons.googlecode.com/files/%s.png'
  591. );
  592. /**
  593. * Get a custom icon set
  594. *
  595. * @param color: green, red, purple, ... or some special ones like "home", ...
  596. * @param char: A...Z or 0...20/100 (defaults to none)
  597. * @param size: s, m, l (defaults to medium)
  598. * NOTE: for special ones only first parameter counts!
  599. * @return array: array(icon, shadow, shape, ...)
  600. * 2011-03-14 ms
  601. */
  602. public function iconSet($color, $char = null, $size = 'm') {
  603. $colors = array('red', 'green', 'yellow', 'blue', 'purple', 'white', 'black');
  604. if (!in_array($color, $colors)) {
  605. $color = 'red';
  606. }
  607. if (!empty($this->_currentOptions['localImages'])) {
  608. $this->setIcons['color'] = $this->_currentOptions['localImages'].'marker%s.png';
  609. $this->setIcons['alpha'] = $this->_currentOptions['localImages'].'marker%s%s.png';
  610. $this->setIcons['numeric'] = $this->_currentOptions['localImages'].'%s%s.png';
  611. $this->setIcons['special'] = $this->_currentOptions['localImages'].'%s.png';
  612. }
  613. if (!empty($char)) {
  614. if ($color === 'red') {
  615. $color = '';
  616. } else {
  617. $color = '_'.$color;
  618. }
  619. $url = sprintf($this->setIcons['alpha'], $color, $char);
  620. } else {
  621. if ($color === 'red') {
  622. $color = '';
  623. } else {
  624. $color = '_'.$color;
  625. }
  626. $url = sprintf($this->setIcons['color'], $color);
  627. }
  628. /*
  629. var iconImage = new google.maps.MarkerImage('images/' + images[0] + '.png',
  630. new google.maps.Size(iconData[images[0]].width, iconData[images[0]].height),
  631. new google.maps.Point(0,0),
  632. new google.maps.Point(0, 32)
  633. );
  634. var iconShadow = new google.maps.MarkerImage('images/' + images[1] + '.png',
  635. new google.maps.Size(iconData[images[1]].width, iconData[images[1]].height),
  636. new google.maps.Point(0,0),
  637. new google.maps.Point(0, 32)
  638. );
  639. var iconShape = {
  640. coord: [1, 1, 1, 32, 32, 32, 32, 1],
  641. type: 'poly'
  642. };
  643. */
  644. $shadow = 'http://www.google.com/mapfiles/shadow50.png';
  645. $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))));
  646. //$this->icons[$ICON_COUNT] = $res;
  647. //$ICON_COUNT++;
  648. return $res;
  649. }
  650. /**
  651. * @param string $imageUrl (http://...)
  652. * @param string $shadowImageUrl (http://...)
  653. * @param array $imageOptions
  654. * @param array $shadowImageOptions
  655. * custom icon: http://thydzik.com/thydzikGoogleMap/markerlink.php?text=?&color=FFFFFF
  656. * custom icons: http://code.google.com/p/google-maps-icons/wiki/NumericIcons#Lettered_Balloons_from_A_to_Z,_in_10_Colors
  657. * custom shadows: http://www.cycloloco.com/shadowmaker/shadowmaker.htm
  658. * 2011-03-13 ms
  659. */
  660. public function addIcon($image, $shadow = null, $imageOptions = array(), $shadowOptions = array()) {
  661. $res = array('url'=>$image);
  662. $res['icon'] = $this->icon($image, $imageOptions);
  663. if ($shadow) {
  664. $last = $this->_iconRemember[$res['icon']];
  665. if (!isset($shadowOptions['anchor'])) {
  666. $shadowOptions['anchor'] = array();
  667. }
  668. $shadowOptions['anchor'] = array_merge($shadowOptions['anchor'], $last['options']['anchor']);
  669. $res['shadow'] = $this->icon($shadow, $shadowOptions);
  670. }
  671. return $res;
  672. }
  673. protected $_iconRemember = array();
  674. /**
  675. * Generate icon object
  676. *
  677. * @param url (required)
  678. * @param options (optional):
  679. * - size: array(width=>x, height=>y)
  680. * - origin: array(width=>x, height=>y)
  681. * - anchor: array(width=>x, height=>y)
  682. */
  683. public function icon($url, $options = array()) {
  684. // The shadow image is larger in the horizontal dimension
  685. // while the position and offset are the same as for the main image.
  686. if (empty($options['size'])) {
  687. if ($data = @getimagesize($url)) {
  688. $options['size']['width'] = $data[0];
  689. $options['size']['height'] = $data[1];
  690. } else {
  691. $options['size']['width'] = $options['size']['height'] = 0;
  692. }
  693. }
  694. if (empty($options['anchor'])) {
  695. $options['anchor']['width'] = intval($options['size']['width']/2);
  696. $options['anchor']['height'] = $options['size']['height'];
  697. }
  698. if (empty($options['origin'])) {
  699. $options['origin']['width'] = $options['origin']['height'] = 0;
  700. }
  701. if (isset($options['shadow'])) {
  702. $options['anchor'] = $options['shadow'];
  703. }
  704. //pr(returns($options));
  705. $icon = 'new google.maps.MarkerImage(\''.$url.'\',
  706. new google.maps.Size('.$options['size']['width'].', '.$options['size']['height'].'),
  707. new google.maps.Point('.$options['origin']['width'].', '.$options['origin']['height'].'),
  708. new google.maps.Point('.$options['anchor']['width'].', '.$options['anchor']['height'].')
  709. )';
  710. $this->icons[self::$ICON_COUNT] = $icon;
  711. $this->_iconRemember[self::$ICON_COUNT] = array('url'=>$url, 'options'=>$options, 'id'=>self::$ICON_COUNT);
  712. //$this->map .= $code;
  713. return self::$ICON_COUNT++;
  714. }
  715. /**
  716. * @param array $options
  717. * - lat, lng, content, maxWidth, pixelOffset, zIndex
  718. * @return int $windowCount
  719. * 2010-12-18 ms
  720. */
  721. public function addInfoWindow($options=array()) {
  722. $options = $this->_currentOptions['infoWindow'];
  723. $options = array_merge($options, $options);
  724. if (!empty($options['lat']) && !empty($options['lng'])) {
  725. $position = "new google.maps.LatLng(".$options['lat'].", ".$options['lng'].")";
  726. } else {
  727. $position = " ".$this->name().".getCenter()";
  728. }
  729. $windows = "
  730. gInfoWindows".self::$MAP_COUNT.".push( new google.maps.InfoWindow({
  731. position: {$position},
  732. content: ".$this->escapeString($options['content']).",
  733. maxWidth: {$options['maxWidth']},
  734. pixelOffset: {$options['pixelOffset']}
  735. /*zIndex: {$options['zIndex']},*/
  736. }));
  737. ";
  738. $this->map .= $windows;
  739. return self::$INFO_WINDOW_COUNT++;
  740. }
  741. /**
  742. * @param int $marker
  743. * @param int $infoWindow
  744. * @return void
  745. * 2010-12-18 ms
  746. */
  747. public function addEvent($marker, $infoWindow) {
  748. $this->map .= "
  749. google.maps.event.addListener(gMarkers[{$marker}], 'click', function() {
  750. gInfoWindows".self::$MAP_COUNT."[$infoWindow].open(".$this->name().", this);
  751. });
  752. ";
  753. }
  754. /**
  755. * @param int $marker
  756. * @param string $event (js)
  757. * @return void
  758. * 2010-12-18 ms
  759. */
  760. public function addCustomEvent($marker, $event) {
  761. $this->map .= "
  762. google.maps.event.addListener(gMarkers".self::$MAP_COUNT."[{$marker}], 'click', function() {
  763. $event
  764. });
  765. ";
  766. }
  767. /**
  768. * @param string $custom (js)
  769. * @return void
  770. * 2010-12-18 ms
  771. */
  772. public function addCustom($js) {
  773. $this->map .= $js;
  774. }
  775. /**
  776. * Add directions to the map
  777. *
  778. * @param array|string $from Location as array(fixed lat/lng pair) or string (to be geocoded at runtime)
  779. * @param array|string $to Location as array(fixed lat/lng pair) or string (to be geocoded at runtime)
  780. * @param array $options
  781. * - directionsDiv: Div to place directions in text form
  782. * - travelMode: TravelMode,
  783. * - transitOptions: TransitOptions,
  784. * - unitSystem: UnitSystem (IMPERIAL, METRIC, AUTO),
  785. * - waypoints[]: DirectionsWaypoint,
  786. * - optimizeWaypoints: Boolean,
  787. * - provideRouteAlternatives: Boolean,
  788. * - avoidHighways: Boolean,
  789. * - avoidTolls: Boolean
  790. * - region: String
  791. * @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRequest
  792. * @return void
  793. */
  794. public function addDirections($from, $to, $options = array()) {
  795. $id = 'd' . self::$MARKER_COUNT++;
  796. $defaults = array(
  797. 'travelMode' => self::TRAVEL_MODE_DRIVING,
  798. 'unitSystem' => 'METRIC',
  799. 'directionsDiv' => null,
  800. );
  801. $options += $defaults;
  802. $travelMode = $this->travelModes[$options['travelMode']];
  803. $directions = "
  804. var {$id}Service = new google.maps.DirectionsService();
  805. var {$id}Display;
  806. {$id}Display = new google.maps.DirectionsRenderer();
  807. {$id}Display.setMap(".$this->name().");
  808. ";
  809. if (!empty($options['directionsDiv'])) {
  810. $directions .= "{$id}Display.setPanel(document.getElementById('" . $options['directionsDiv'] . "'));";
  811. }
  812. if (is_array($from)) {
  813. $from = 'new google.maps.LatLng(' . (float)$from['lat'] . ', ' . (float)$from['lng'] . ')';
  814. } else {
  815. $from = '\'' . h($from) . '\'';
  816. }
  817. if (is_array($to)) {
  818. $to = 'new google.maps.LatLng(' . (float)$to['lat'] . ', ' . (float)$to['lng'] . ')';
  819. } else {
  820. $to = '\'' . h($to) . '\'';
  821. }
  822. $directions .= "
  823. var request = {
  824. origin: $from,
  825. destination: $to,
  826. unitSystem: google.maps.UnitSystem.".$options['unitSystem'].",
  827. travelMode: google.maps.TravelMode.$travelMode
  828. };
  829. {$id}Service.route(request, function(result, status) {
  830. if (status == google.maps.DirectionsStatus.OK) {
  831. {$id}Display.setDirections(result);
  832. }
  833. });
  834. ";
  835. $this->map .= $directions;
  836. }
  837. /**
  838. * Add a polyline
  839. *
  840. * This method adds a line between 2 points
  841. *
  842. * @param array|string $from Location as array(fixed lat/lng pair) or string (to be geocoded at runtime)
  843. * @param array|string $to Location as array(fixed lat/lng pair) or string (to be geocoded at runtime)
  844. * @param array $options
  845. * - color (#FFFFFF ... #000000)
  846. * - opacity (0.1 ... 1, defaults to 1)
  847. * - weight in pixels (defaults to 2)
  848. * @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline
  849. * @return void
  850. */
  851. public function addPolyline($from, $to, $options = array()) {
  852. if (is_array($from)) {
  853. $from = 'new google.maps.LatLng(' . (float)$from['lat'] . ', ' . (float)$from['lng'] . ')';
  854. } else {
  855. throw new CakeException('not implemented yet, use array of lat/lng');
  856. $from = '\'' . h($from) . '\'';
  857. }
  858. if (is_array($to)) {
  859. $to = 'new google.maps.LatLng(' . (float)$to['lat'] . ', ' . (float)$to['lng'] . ')';
  860. } else {
  861. throw new CakeException('not implemented yet, use array of lat/lng');
  862. $to = '\'' . h($to) . '\'';
  863. }
  864. $defaults = array(
  865. 'color' => '#FF0000',
  866. 'opacity' => 1.0,
  867. 'weight' => 2,
  868. );
  869. $options += $defaults;
  870. if( !isset($strokeColor) ) $strokeColor = $this->defaultStrokeColor;
  871. if( !isset($strokeOpacity) ) $strokeOpacity = $this->defaultStrokeOpacity;
  872. if( !isset($strokeWeight) ) $strokeWeight = $this->defaultStrokeWeight;
  873. $id = 'p' . self::$MARKER_COUNT++;
  874. $polyline = "var start = $from;";
  875. $polyline .= "var end = $to;";
  876. $polyline .= "
  877. var poly = [
  878. start,
  879. end
  880. ];
  881. var {$id}Polyline = new google.maps.Polyline({
  882. path: poly,
  883. strokeColor: '" . $options['color'] . "',
  884. strokeOpacity: " . $options['opacity'] . ",
  885. strokeWeight: " . $options['weight'] . "
  886. });
  887. {$id}Polyline.setMap(".$this->name().");
  888. ";
  889. $this->map .= $polyline;
  890. }
  891. /**
  892. * @param string $content (html/text)
  893. * @param int $infoWindowCount
  894. * @return void
  895. * 2010-12-18 ms
  896. */
  897. public function setContentInfoWindow($con, $index) {
  898. $this->map .= "
  899. gInfoWindows".self::$MAP_COUNT."[$index].setContent(".$this->escapeString($con).");";
  900. }
  901. /**
  902. * json encode string
  903. *
  904. * @param mixed $content
  905. * @return json
  906. */
  907. public function escapeString($content) {
  908. return json_encode($content);
  909. }
  910. /**
  911. * This method returns the javascript for the current map container.
  912. * Including script tags.
  913. * Just echo it below the map container. New: Alternativly, use finalize() directly.
  914. *
  915. * @return string
  916. * 2010-12-18 ms
  917. */
  918. public function script() {
  919. $script = '<script type="text/javascript">
  920. '.$this->finalize(true).'
  921. </script>';
  922. return $script;
  923. }
  924. /**
  925. * Finalize the map and write the javascript to the buffer.
  926. * Make sure that your view does also output the buffer at some place!
  927. *
  928. * @param boolean $return If the output should be returned instead
  929. * @return void or string Javascript if $return is true
  930. */
  931. public function finalize($return = false) {
  932. $script = $this->_arrayToObject('matching', $this->matching, false, true).'
  933. '.$this->_arrayToObject('gIcons'.self::$MAP_COUNT, $this->icons, false, false).'
  934. jQuery(document).ready(function() {
  935. ';
  936. $script .= $this->map;
  937. if ($this->_currentOptions['geolocate']) {
  938. $script .= $this->_geolocate();
  939. }
  940. if ($this->_currentOptions['showMarker'] && !empty($this->markers) && is_array($this->markers)) {
  941. $script .= implode($this->markers, " ");
  942. }
  943. if ($this->_currentOptions['autoCenter']) {
  944. $script .= $this->_autoCenter();
  945. }
  946. $script .= '
  947. });';
  948. self::$MAP_COUNT++;
  949. if ($return) {
  950. return $script;
  951. }
  952. $this->Js->buffer($script);
  953. }
  954. /**
  955. * set a custom geolocate callback
  956. * @param string $customJs
  957. * false: no callback at all
  958. * @return void
  959. * 2011-03-16 ms
  960. */
  961. public function geolocateCallback($js) {
  962. if ($js === false) {
  963. $this->_currentOptions['callbacks']['geolocate'] = false;
  964. return;
  965. }
  966. $this->_currentOptions['callbacks']['geolocate'] = $js;
  967. }
  968. /**
  969. * experimental - works in cutting edge browsers like chrome10
  970. * 2011-03-16 ms
  971. */
  972. protected function _geolocate() {
  973. return '
  974. // Try W3C Geolocation (Preferred)
  975. if (navigator.geolocation) {
  976. browserSupportFlag = true;
  977. navigator.geolocation.getCurrentPosition(function(position) {
  978. geolocationCallback(position.coords.latitude, position.coords.longitude);
  979. }, function() {
  980. handleNoGeolocation(browserSupportFlag);
  981. });
  982. // Try Google Gears Geolocation
  983. } else if (google.gears) {
  984. browserSupportFlag = true;
  985. var geo = google.gears.factory.create(\'beta.geolocation\');
  986. geo.getCurrentPosition(function(position) {
  987. geolocationCallback(position.latitude, position.longitude);
  988. }, function() {
  989. handleNoGeoLocation(browserSupportFlag);
  990. });
  991. // Browser doesn\'t support Geolocation
  992. } else {
  993. browserSupportFlag = false;
  994. handleNoGeolocation(browserSupportFlag);
  995. }
  996. function geolocationCallback(lat, lng) {
  997. '.$this->_geolocationCallback().'
  998. }
  999. function handleNoGeolocation(errorFlag) {
  1000. if (errorFlag == true) {
  1001. //alert("Geolocation service failed.");
  1002. } else {
  1003. //alert("Your browser doesn\'t support geolocation. We\'ve placed you in Siberia.");
  1004. }
  1005. //'.$this->name().'.setCenter(initialLocation);
  1006. }
  1007. ';
  1008. }
  1009. protected function _geolocationCallback() {
  1010. if (($js = $this->_currentOptions['callbacks']['geolocate']) === false) {
  1011. return '';
  1012. }
  1013. if ($js === null) {
  1014. $js = 'initialLocation = new google.maps.LatLng(lat, lng);
  1015. '.$this->name().'.setCenter(initialLocation);
  1016. ';
  1017. }
  1018. return $js;
  1019. }
  1020. /**
  1021. * auto center map
  1022. * careful: with only one marker this can result in too high zoom values!
  1023. * @return string $autoCenterCommands
  1024. * 2010-12-17 ms
  1025. */
  1026. protected function _autoCenter() {
  1027. return '
  1028. var bounds = new google.maps.LatLngBounds();
  1029. $.each(gMarkers'.self::$MAP_COUNT.',function (index, marker) { bounds.extend(marker.position);});
  1030. '.$this->name().'.fitBounds(bounds);
  1031. ';
  1032. }
  1033. /**
  1034. * @return json like js string
  1035. * 2010-12-17 ms
  1036. */
  1037. protected function _mapOptions() {
  1038. $options = array_merge($this->_currentOptions, $this->_currentOptions['map']);
  1039. $mapOptions = array_intersect_key($options, array(
  1040. 'streetViewControl' => null,
  1041. 'navigationControl' => null,
  1042. 'mapTypeControl' => null,
  1043. 'scaleControl' => null,
  1044. 'scrollwheel' => null,
  1045. 'zoom' => null,
  1046. 'keyboardShortcuts' => null
  1047. ));
  1048. $res = array();
  1049. foreach ($mapOptions as $key => $mapOption) {
  1050. $res[] = $key.': '.$this->Js->value($mapOption);
  1051. }
  1052. if (empty($options['autoCenter'])) {
  1053. $res[] = 'center: initialLocation';
  1054. }
  1055. if (!empty($options['navOptions'])) {
  1056. $res[] = 'navigationControlOptions: '.$this->_controlOptions('nav', $options['navOptions']);
  1057. }
  1058. if (!empty($options['typeOptions'])) {
  1059. $res[] = 'mapTypeControlOptions: '.$this->_controlOptions('type', $options['typeOptions']);
  1060. }
  1061. if (!empty($options['scaleOptions'])) {
  1062. $res[] = 'scaleControlOptions: '.$this->_controlOptions('scale', $options['scaleOptions']);
  1063. }
  1064. if (array_key_exists($options['type'], $this->types)) {
  1065. $type = $this->types[$options['type']];
  1066. } else {
  1067. $type = $options['type'];
  1068. }
  1069. $res[] = 'mapTypeId: google.maps.MapTypeId.'.$type;
  1070. return '{'.implode(', ', $res).'}';
  1071. }
  1072. /**
  1073. * @return json like js string
  1074. * 2010-12-17 ms
  1075. */
  1076. protected function _controlOptions($type, $options) {
  1077. $mapping = array(
  1078. 'nav' => 'NavigationControlStyle',
  1079. 'type' => 'MapTypeControlStyle',
  1080. 'scale' => ''
  1081. );
  1082. $res = array();
  1083. if (!empty($options['style']) && ($m = $mapping[$type])) {
  1084. $res[] = 'style: google.maps.'.$m.'.'.$options['style'];
  1085. }
  1086. if (!empty($options['pos'])) {
  1087. $res[] = 'position: google.maps.ControlPosition.'.$options['pos'];
  1088. }
  1089. return '{'.implode(', ', $res).'}';
  1090. }
  1091. /** Google Maps Link **/
  1092. /**
  1093. * returns a maps.google link
  1094. *
  1095. * @param string $linkTitle
  1096. * @param array $mapOptions
  1097. * @param array $linkOptions
  1098. * @return string Html link
  1099. * 2011-03-12 ms
  1100. */
  1101. public function mapLink($title, $mapOptions = array(), $linkOptions = array()) {
  1102. return $this->Html->link($title, $this->mapUrl($mapOptions), $linkOptions);
  1103. }
  1104. /**
  1105. * returns a maps.google url
  1106. *
  1107. * @param array options:
  1108. * - from: necessary (address or lat,lng)
  1109. * - to: 1x necessary (address or lat,lng - can be an array of multiple destinations: array('dest1', 'dest2'))
  1110. * - zoom: optional (defaults to none)
  1111. * @return string link: http://...
  1112. * 2010-12-18 ms
  1113. */
  1114. public function mapUrl($options = array()) {
  1115. $url = $this->_protocol() . 'maps.google.com/maps?';
  1116. $urlArray = array();
  1117. if (!empty($options['from'])) {
  1118. $urlArray[] = 'saddr=' . urlencode($options['from']);
  1119. }
  1120. if (!empty($options['to']) && is_array($options['to'])) {
  1121. $to = array_shift($options['to']);
  1122. foreach ($options['to'] as $key => $value) {
  1123. $to .= '+to:' . $value;
  1124. }
  1125. $urlArray[] = 'daddr=' . urlencode($to);
  1126. } elseif (!empty($options['to'])) {
  1127. $urlArray[] = 'daddr=' . urlencode($options['to']);
  1128. }
  1129. if (!empty($options['zoom'])) {
  1130. $urlArray[] = 'z=' . (int)$options['zoom'];
  1131. }
  1132. //$urlArray[] = 'f=d';
  1133. //$urlArray[] = 'hl=de';
  1134. //$urlArray[] = 'ie=UTF8';
  1135. return $url . (implode('&', $urlArray));
  1136. }
  1137. /** STATIC MAP **/
  1138. /** 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 **/
  1139. /**
  1140. * Create a plain image map
  1141. * @link http://code.google.com/intl/de-DE/apis/maps/documentation/staticmaps
  1142. * @param options:
  1143. * - string $size [necessary: VALxVAL, e.g. 500x400 - max 640x640]
  1144. * - string $center: x,y or address [necessary, if no markers are given; else tries to take defaults if available] or TRUE/FALSE
  1145. * - int $zoom [optional; if no markers are given, default value is used; if set to "auto" and ]*
  1146. * - array $markers [optional, @see staticPaths() method]
  1147. * - string $type [optional: roadmap/hybrid, ...; default:roadmap]
  1148. * - string $mobile TRUE/FALSE
  1149. * - string $visible: $area (x|y|...)
  1150. * - array $paths [optional, @see staticPaths() method]
  1151. * - string $language [optional]
  1152. * @param array $attributes: html attributes for the image
  1153. * - title
  1154. * - alt (defaults to 'Map')
  1155. * - url (tip: you can pass $this->link(...) and it will create a link to maps.google.com)
  1156. * @return string $imageTag
  1157. * 2010-12-18 ms
  1158. */
  1159. public function staticMap($options = array(), $attributes = array()) {
  1160. $defaultAttributes = array('alt' => __('Map'));
  1161. return $this->Html->image($this->staticMapUrl($options), array_merge($defaultAttributes, $attributes));
  1162. }
  1163. /**
  1164. * Create a link to a plain image map
  1165. * @param string $linkTitle
  1166. * @param array $mapOptions
  1167. * @param array $linkOptions
  1168. * @return string Html link
  1169. * 2011-03-12 ms
  1170. */
  1171. public function staticMapLink($title, $mapOptions = array(), $linkOptions = array()) {
  1172. return $this->Html->link($title, $this->staticMapUrl($mapOptions), $linkOptions);
  1173. }
  1174. /**
  1175. * Create an url to a plain image map
  1176. * @param options
  1177. * - see staticMap() for details
  1178. * @return string $urlOfImage: http://...
  1179. * 2010-12-18 ms
  1180. */
  1181. public function staticMapUrl($options = array()) {
  1182. $map = $this->_protocol() . self::STATIC_API;
  1183. /*
  1184. $params = array(
  1185. 'sensor' => 'false',
  1186. 'mobile' => 'false',
  1187. 'format' => 'png',
  1188. //'center' => false
  1189. );
  1190. if (!empty($options['sensor'])) {
  1191. $params['sensor'] = 'true';
  1192. }
  1193. if (!empty($options['mobile'])) {
  1194. $params['mobile'] = 'true';
  1195. }
  1196. */
  1197. $defaults = array_merge($this->_defaultOptions, $this->_defaultOptions['staticMap']);
  1198. $mapOptions = array_merge($defaults, $options);
  1199. $params = array_intersect_key($mapOptions, array(
  1200. 'sensor' => null,
  1201. 'mobile' => null,
  1202. 'format' => null,
  1203. 'size' => null,
  1204. //'zoom' => null,
  1205. //'lat' => null,
  1206. //'lng' => null,
  1207. //'visible' => null,
  1208. //'type' => null,
  1209. ));
  1210. # do we want zoom to auto-correct itself?
  1211. if (!isset($options['zoom']) && !empty($mapOptions['markers'])|| !empty($mapOptions['paths']) || !empty($mapOptions['visible'])) {
  1212. $options['zoom'] = 'auto';
  1213. }
  1214. # a position on the map that is supposed to stay visible at all cost
  1215. if (!empty($mapOptions['visible'])) {
  1216. $params['visible'] = urlencode($mapOptions['visible']);
  1217. }
  1218. # center and zoom are not necccessary if path, visible or markers are given
  1219. if (!isset($options['center']) || $options['center'] === false) {
  1220. # dont use it
  1221. } elseif ($options['center'] === true && $mapOptions['lat'] !== null && $mapOptions['lng'] !== null) {
  1222. $params['center'] = urlencode((string)$mapOptions['lat'] . ',' . (string)$mapOptions['lng']);
  1223. } elseif (!empty($options['center'])) {
  1224. $params['center'] = urlencode($options['center']);
  1225. } /*else {
  1226. # try to read from markers array???
  1227. if (isset($options['markers']) && count($options['markers']) == 1) {
  1228. //pr ($options['markers']);
  1229. }
  1230. }*/
  1231. if (!isset($options['zoom']) || $options['zoom'] === false) {
  1232. # dont use it
  1233. } else {
  1234. if ($options['zoom'] === 'auto') {
  1235. if (!empty($options['markers']) && strpos($options['zoom'],'|') !== false) {
  1236. # let google find the best zoom value itself
  1237. } else {
  1238. # do something here?
  1239. }
  1240. } else {
  1241. $params['zoom'] = $options['zoom'];
  1242. }
  1243. }
  1244. if (array_key_exists($mapOptions['type'], $this->types)) {
  1245. $params['maptype'] = $this->types[$mapOptions['type']];
  1246. } else {
  1247. $params['maptype'] = $mapOptions['type'];
  1248. }
  1249. //unset($options['type']);
  1250. $params['maptype'] = strtolower($params['maptype']);
  1251. # old: {latitude},{longitude},{color}{alpha-character}
  1252. # new: @see staticMarkers()
  1253. if (!empty($options['markers'])) {
  1254. $params['markers'] = $options['markers'];
  1255. }
  1256. if (!empty($options['paths'])) {
  1257. $params['path'] = $options['paths'];
  1258. }
  1259. # valXval
  1260. if (!empty($options['size'])) {
  1261. $params['size'] = $options['size'];
  1262. }
  1263. $pieces = array();
  1264. foreach ($params as $key => $value) {
  1265. if (is_array($value)) {
  1266. $value = implode('&'.$key.'=', $value);
  1267. } elseif ($value === true) {
  1268. $value = 'true';
  1269. } elseif ($value === false) {
  1270. $value = 'false';
  1271. } elseif ($value === null) {
  1272. continue;
  1273. }
  1274. $pieces[] = $key.'='.$value;
  1275. //$map .= $key.'='.$value.'&';
  1276. }
  1277. return $map . (implode('&', $pieces));
  1278. }
  1279. /**
  1280. * prepare paths for staticMap
  1281. * @param array $pathElementArrays
  1282. * - elements: [required] (multiple array(lat=>x, lng=>y) or just a address strings)
  1283. * - color: red/blue/green (optional, default blue)
  1284. * - weight: numeric (optional, default: 5)
  1285. * @return string $paths: e.g: color:0x0000FF80|weight:5|37.40303,-122.08334|37.39471,-122.07201|37.40589,-122.06171{|...}
  1286. * 2010-12-18 ms
  1287. */
  1288. public function staticPaths($pos = array()) {
  1289. $defaults = array(
  1290. 'color' => 'blue',
  1291. 'weight' => 5 # pixel
  1292. );
  1293. # not a 2-level array? make it one
  1294. if (!isset($pos[0])) {
  1295. $pos = array($pos);
  1296. }
  1297. $res = array();
  1298. foreach ($pos as $p) {
  1299. $options = array_merge($defaults, $p);
  1300. $markers = $options['path'];
  1301. unset($options['path']);
  1302. # prepare color
  1303. if (!empty($options['color'])) {
  1304. $options['color'] = $this->_prepColor($options['color']);
  1305. }
  1306. $path = array();
  1307. foreach ($options as $key => $value) {
  1308. $path[] = $key.':'.urlencode($value);
  1309. }
  1310. foreach ($markers as $key => $pos) {
  1311. if (is_array($pos)) {
  1312. # lat/lng?
  1313. $pos = $pos['lat'].','.$pos['lng'];
  1314. }
  1315. $path[] = $pos;
  1316. }
  1317. $res[] = implode('|', $path);
  1318. }
  1319. return $res;
  1320. }
  1321. /**
  1322. * prepare markers for staticMap
  1323. * @param array $markerArrays
  1324. * - lat: xx.xxxxxx (necessary)
  1325. * - lng: xx.xxxxxx (necessary)
  1326. * - address: (instead of lat/lng)
  1327. * - color: red/blue/green (optional, default blue)
  1328. * - label: a-z or numbers (optional, default: s)
  1329. * - icon: custom icon (png, gif, jpg - max 64x64 - max 5 different icons per image)
  1330. * - shadow: TRUE/FALSE
  1331. * @param style (global) (overridden by custom marker styles)
  1332. * - color
  1333. * - label
  1334. * - icon
  1335. * - shadow
  1336. * @return array $markers: color:green|label:Z|48,11|Berlin
  1337. *
  1338. * NEW: size:mid|color:red|label:E|37.400465,-122.073003|37.437328,-122.159928&markers=size:small|color:blue|37.369110,-122.096034
  1339. * OLD: 40.702147,-74.015794,blueS|40.711614,-74.012318,greenG{|...}
  1340. * 2010-12-18 ms
  1341. */
  1342. public function staticMarkers($pos = array(), $style = array()) {
  1343. $markers = array();
  1344. $verbose = false;
  1345. $defaults = array(
  1346. 'shadow' => 'true',
  1347. 'color' => 'blue',
  1348. 'label' => '',
  1349. 'address' => '',
  1350. 'size' => ''
  1351. );
  1352. # not a 2-level array? make it one
  1353. if (!isset($pos[0])) {
  1354. $pos = array($pos);
  1355. }
  1356. # new in statitV2: separate styles! right now just merged
  1357. foreach ($pos as $p) {
  1358. $p = array_merge($defaults, $style, $p);
  1359. # adress or lat/lng?
  1360. if (!empty($p['lat']) && !empty($p['lng'])) {
  1361. $p['address'] = $p['lat'].','.$p['lng'];
  1362. } else {
  1363. $p['address'] = $p['address'];
  1364. }
  1365. $p['address'] = urlencode($p['address']);
  1366. $values = array();
  1367. # prepare color
  1368. if (!empty($p['color'])) {
  1369. $p['color'] = $this->_prepColor($p['color']);
  1370. $values[] = 'color:'.$p['color'];
  1371. }
  1372. # label? A-Z0-9
  1373. if (!empty($p['label'])) {
  1374. $values[] = 'label:'.strtoupper($p['label']);
  1375. }
  1376. if (!empty($p['size'])) {
  1377. $values[] = 'size:'.$p['size'];
  1378. }
  1379. if (!empty($p['shadow'])) {
  1380. $values[] = 'shadow:'.$p['shadow'];
  1381. }
  1382. if (!empty($p['icon'])) {
  1383. $values[] = 'icon:'.urlencode($p['icon']);
  1384. }
  1385. $values[] = $p['address'];
  1386. //TODO: icons
  1387. $markers[] = implode('|', $values);
  1388. }
  1389. //TODO: shortcut? only possible if no custom params!
  1390. if ($verbose) {
  1391. }
  1392. // long: markers=styles1|address1&markers=styles2|address2&...
  1393. // short: markers=styles,address1|address2|address3|...
  1394. return $markers;
  1395. }
  1396. /**
  1397. * Ensure that we stay on the appropriate protocol
  1398. *
  1399. * @return string protocol base (including ://)
  1400. */
  1401. protected function _protocol() {
  1402. if (($https = $this->_currentOptions['https']) === null) {
  1403. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
  1404. }
  1405. return ($https ? 'https' : 'http') . '://';
  1406. }
  1407. /**
  1408. * # to 0x
  1409. * or # added
  1410. * @param string $color: FFFFFF, #FFFFFF, 0xFFFFFF or blue
  1411. * @return string $color
  1412. * 2010-12-20 ms
  1413. */
  1414. protected function _prepColor($color) {
  1415. if (strpos($color, '#') !== false) {
  1416. return str_replace('#', '0x', $color);
  1417. } elseif (is_numeric($color)) {
  1418. return '0x'.$color;
  1419. }
  1420. return $color;
  1421. }
  1422. /** TODOS/EXP **/
  1423. /*
  1424. TODOS:
  1425. - animations
  1426. marker.setAnimation(google.maps.Animation.BOUNCE);
  1427. - geocoding (+ reverse)
  1428. - directions
  1429. - overlays
  1430. - fluster (for clustering?)
  1431. or
  1432. - markerManager (many markers)
  1433. - infoBox
  1434. http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/
  1435. - ...
  1436. */
  1437. public function geocoder() {
  1438. $js = 'var geocoder = new google.maps.Geocoder();';
  1439. //TODO
  1440. }
  1441. /**
  1442. * managing lots of markers!
  1443. * @link http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/docs/examples.html
  1444. * @param options
  1445. * -
  1446. * @return void
  1447. * 2010-12-18 ms
  1448. */
  1449. public function setManager() {
  1450. $js .= '
  1451. var mgr'.self::$MAP_COUNT.' = new MarkerManager('.$this->name().');
  1452. ';
  1453. }
  1454. public function addManagerMarker($marker, $options) {
  1455. $js = 'mgr'.self::$MAP_COUNT.'.addMarker('.$marker.');';
  1456. }
  1457. /**
  1458. * clustering for lots of markers!
  1459. * @link ?
  1460. * @param options
  1461. * -
  1462. * based on Fluster2 0.1.1
  1463. * @return void
  1464. */
  1465. public function setCluster($options) {
  1466. $js = self::$flusterScript;
  1467. $js .= '
  1468. var fluster'.self::$MAP_COUNT.' = new Fluster2('.$this->name().');
  1469. ';
  1470. # styles
  1471. 'fluster'.self::$MAP_COUNT.'.styles = {}';
  1472. $this->map .= $js;
  1473. }
  1474. public function addClusterMarker($marker, $options) {
  1475. $js = 'fluster'.self::$MAP_COUNT.'.addMarker('.$marker.');';
  1476. }
  1477. public function initCluster() {
  1478. $this->map .= 'fluster'.self::$MAP_COUNT.'.initialize();';
  1479. }
  1480. public static $flusterScript = '
  1481. 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)}}
  1482. 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)}
  1483. 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\'};
  1484. 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() {};
  1485. \'';
  1486. /** CALCULATING STUFF **/
  1487. /**
  1488. * Calculates Distance between two points array('lat'=>x,'lng'=>y)
  1489. * DB:
  1490. '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  1491. 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
  1492. 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
  1493. 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
  1494. 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
  1495. 'AS distance'
  1496. * @param array pointX
  1497. * @param array pointY
  1498. * @return int distance: in km
  1499. * DEPRECATED - use GeocodeLib::distance() instead!
  1500. * 2009-03-06 ms
  1501. */
  1502. public function distance($pointX, $pointY) {
  1503. /*
  1504. $res = 6371.04 * ACOS( COS( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  1505. COS( PI()/2 - rad2deg(90 - $pointY['lat'])) *
  1506. COS( rad2deg($pointX['lng']) - rad2deg($pointY['lng'])) +
  1507. SIN( PI()/2 - rad2deg(90 - $pointX['lat'])) *
  1508. SIN( PI()/2 - rad2deg(90 - $pointY['lat'])));
  1509. $res = 6371.04 * acos(sin($pointY['lat'])*sin($pointX['lat'])+cos($pointY['lat'])*cos($pointX['lat'])*cos($pointY['lng'] - $pointX['lng']));
  1510. */
  1511. # seems to be the only working one (although slightly incorrect...)
  1512. $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']))));
  1513. # Miles to KM
  1514. $res *= 1.609344;
  1515. return ceil($res);
  1516. }
  1517. protected function _arrayToObject($name, $array, $asString = true, $keyAsString = false) {
  1518. $res = 'var '.$name.' = {'.PHP_EOL;
  1519. $res .= $this->_toObjectParams($array, $asString, $keyAsString);
  1520. $res .= '};';
  1521. return $res;
  1522. }
  1523. protected function _toObjectParams($array, $asString = true, $keyAsString = false) {
  1524. $pieces = array();
  1525. foreach ($array as $key => $value) {
  1526. $e = ($asString && strpos($value, 'new ') !== 0 ? '\'' : '');
  1527. $ke = ($keyAsString ? '\'' : '');
  1528. $pieces[] = $ke.$key.$ke.': '.$e.$value.$e;
  1529. }
  1530. return implode(','.PHP_EOL, $pieces);
  1531. }
  1532. }