GoogleMapV3Helper.php 51 KB

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