GoogleMapV3Helper.php 56 KB

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