GoogleMapV3Helper.php 57 KB

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