GoogleMapV3Helper.php 56 KB

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