GoogleMapV3Helper.php 54 KB

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