GoogleMapV3Helper.php 57 KB

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