GoogleMapV3Helper.php 56 KB

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