Development

/plugins/sfEasyGMapPlugin/trunk/lib/GMap.class.php

You must first sign up to be able to contribute.

root/plugins/sfEasyGMapPlugin/trunk/lib/GMap.class.php

Revision 21816, 15.8 kB (checked in by laurentb, 3 years ago)

[sfEasyGMapPlugin][trunk] Tabs to spaces

Line 
1 <?php
2
3 /**
4  * Google Map class
5  * @author Fabrice Bernhard
6  */
7
8 class GMap
9 {
10  
11   protected $default_options = array(
12       'double_click_zoom' => true,
13       'control' => array('new google.maps.LargeMapControl()'),
14       'zoom' => 10,
15       'center_lat' => 48.845398,
16       'center_lng' => 2.34258,
17       'js_name' => 'map'
18   );
19   // The API key provided by Google
20   protected $api_key;
21
22   // id of the Google Map div container
23   protected $container_attributes = array(
24       'id' =>'map'
25   );
26   // style of the container
27   protected $container_style=array('width'=>'512px','height'=>'512px');
28
29   // objects linked to the map
30   protected $icons=array();
31   protected $markers=array();
32   protected $events=array();
33
34   // customise the javascript generated
35   protected $after_init_js=array();
36   protected $global_variables=array();
37
38   // options
39   protected $options = array();
40  
41   protected $zoom = null;
42   protected $center_coord = null;
43
44   /**
45    * Constructs a Google Map PHP object
46    *
47    * @param array $options
48    * @param array $attributes
49    */
50   public function __construct($options=array(),$container_attributes=array())
51   {
52     $this->options = array_merge($this->default_options,$options);
53     $this->container_attributes = array_merge($this->container_attributes,$container_attributes);
54     // sets the starting zoom and center parameters
55     $this->zoom = $this->options['zoom'];
56     $this->setCenter($this->options['center_lat'], $this->options['center_lng']);
57
58     // delcare the Google Map Javascript object as global
59     $this->addGlobalVariable($this->getJsName(),'null');
60
61     // set the Google Map API key for the current domain
62     $this->guessAndSetAPIKey();
63
64   }
65
66   /**
67    * Guesses and sets the API Key
68    * @author Fabrice
69    *
70    */
71   protected function guessAndSetAPIKey()
72   {
73     $this->setAPIKey(self::guessAPIKey());
74   }
75  
76   /**
77    * Sets the Google Map API Key using the array_google_keys defined in the app.yml of your application
78    * @param string $domain The domaine name
79    * @author Fabrice
80    *
81    */
82   public function setAPIKeyByDomain($domain)
83   {
84     $this->setAPIKey(self::getAPIKeyByDomain($domain));
85   }
86     
87   /**
88    * Guesses the GoogleMap key for the current domain
89    * @return string $api_key
90    * @author Fabrice
91    *
92    */
93   public static function guessAPIKey()
94   {
95     if (isset($_SERVER['SERVER_NAME']))
96     {
97       return self::getAPIKeyByDomain($_SERVER['SERVER_NAME']);
98     }
99     else if (isset($_SERVER['HTTP_HOST']))
100     {
101       return self::getAPIKeyByDomain($_SERVER['HTTP_HOST']);
102     }
103
104     return self::getAPIKeyByDomain('default');
105   }
106
107   /**
108    * Static method to retrieve API key
109    *
110    * @param unknown_type $domain
111    * @return unknown
112    */
113   public static function getAPIKeyByDomain($domain)
114   {
115     $api_keys = sfConfig::get('app_google_maps_api_keys');
116     if (is_null($api_keys))
117     {
118       return '';
119     }
120     
121     if (is_array($api_keys) && array_key_exists($domain,$api_keys))
122     {
123       $api_key=$api_keys[$domain];
124     }
125     else
126     {
127       if (array_key_exists('default',$api_keys))
128       {
129         $api_key=$api_keys['default'];
130       }
131       else
132       {
133         throw new sfException('No Google Map API key defined in the app.yml file of your application');
134       }
135     }
136     
137     return $api_key;
138   }
139
140
141   /**
142    * Geocodes an address
143    * @param string $address
144    * @return GMapGeocodedAddress
145    * @author Fabrice Bernhard
146    */
147   public function geocode($address)
148   {
149     $gMapGeocodedAddress = new GMapGeocodedAddress($address);
150     $gMapGeocodedAddress->geocode($this->getAPIKey());
151
152     return $gMapGeocodedAddress;
153   }
154   /**
155    * Geocodes an address and returns additional normalized information
156    * @param string $address
157    * @return GMapGeocodedAddress
158    * @author Fabrice Bernhard
159    */
160   public function geocodeXml($address)
161   {
162     $gMapGeocodedAddress = new GMapGeocodedAddress($address);
163     $gMapGeocodedAddress->geocodeXml($this->getAPIKey());
164
165     return $gMapGeocodedAddress;
166   }
167
168   /**
169    * @return string $this->options['js_name'] Javascript name of the googlemap
170    */
171   public function getJsName()
172   {
173
174     return $this->options['js_name'];
175   }
176
177   /**
178    * Sets the Google Maps API key
179    * @param string $key
180    */
181   public function setAPIKey($key)
182   {
183     $this->api_key=$key;
184   }
185   /**
186    * Gets the Google Maps API key
187    * @return string $key
188    */
189   public function getAPIKey()
190   {
191
192     return $this->api_key;
193   }
194
195   /**
196    * Defines the style of the Google Map div
197    * @param Array $style Associative array with the style of the div container
198    */
199   public function setContainerStyles($style)
200   {
201     $this->container_style=$style;
202   }
203   /**
204    * Defines one style of the div container
205    * @param string $style_tag name of css tag
206    * @param string $style_value value of css tag
207    */
208   public function setContainerStyle($style_tag,$style_value)
209   {
210     $this->container_style[$style_tag]=$style_value;
211   }
212   /**
213    * Gets the style Array of the div container
214    */
215   public function getContainerStyles()
216   {
217
218     return $this->container_style;
219   }
220
221   /*
222    * Gets one style of the Google Map div
223    * @param string $style_tag name of css tag
224    */
225   public function getContainerStyle($style_tag)
226   {
227
228     return $this->container_style[$style_tag];
229   }
230  
231   public function getContainerId()
232   {
233     
234     return $this->container_attributes['id'];
235   }
236
237   /**
238    * returns the Html for the Google map container
239    * @param Array $options Style options of the HTML container
240    * @return string $container
241    * @author Fabrice Bernhard
242    */
243   public function getContainer($styles=array(),$attributes=array())
244   {
245     $this->container_style = array_merge($this->container_style,$styles);
246     $this->container_attributes = array_merge($this->container_attributes,$attributes);
247
248     $style="";
249     foreach ($this->container_style as $tag=>$val)
250     {
251       $style.=$tag.":".$val.";";
252     }
253     
254     $attributes = $this->container_attributes;
255     $attributes['style'] = $style;
256     
257     return RenderTag::renderContent('div',null,$attributes);
258   }
259
260
261   /**
262    * Returns the Javascript for the Google map
263    * @param Array $options
264    * @return $string
265    * @author Fabrice Bernhard
266    * @since 2009-04-23 tomr changed control from string to array
267    * @since 2009-05-03 fabriceb added backwards compatibility
268    */
269   public function getJavascript()
270   {
271     sfContext::getInstance()->getResponse()->addJavascript($this->getGoogleJsUrl());
272
273     $options = $this->options;
274
275     $return ='';
276     $init_events = array();
277     $init_events[] = $this->getJsName().' = new google.maps.Map2(document.getElementById("'.$this->getContainerId().'"));';
278     $init_events[] = $this->getJsName().'.setCenter(new google.maps.LatLng('.$this->getCenterLat().', '.$this->getCenterLng().'), '.$this->getZoom().');';
279     if ($options['double_click_zoom'])
280     {
281       $init_events[] = $this->getJsName().'.enableDoubleClickZoom();';
282     }
283     if (is_array($options['control']))
284     {
285       foreach ($options['control'] as $control)
286       {
287         $init_events[] = $this->getJsName().'.addControl('.$control.');';
288       }
289     }
290     else if ($options['control'] != '')
291     {
292       $init_events[] = $this->getJsName().'.addControl('.$options['control'].');';
293     }
294     $init_events[] = $this->getEventsJs();
295     $this->loadMarkerIcons();
296     $init_events[] = $this->getIconsJs();
297     $init_events[] = $this->getMarkersJs();
298     foreach ($this->after_init_js as $after_init)
299     {
300       $init_events[] = $after_init;
301     }
302
303     $return .= '
304   google.load("maps", "2");
305     ';
306     foreach($this->global_variables as $name=>$value)
307     {
308       $return .= '
309   var '.$name.' = '.$value.';';
310     }
311     $return .= '
312   //  Call this function when the page has been loaded
313   function initialize()
314   {
315     if (GBrowserIsCompatible())
316     {';
317     foreach($init_events as $init_event)
318     {
319       $return .= '
320       '.$init_event;
321     }
322     $return .= '
323     }
324   }
325   google.setOnLoadCallback(initialize);
326   document.onunload="GUnload()";
327 ';
328
329     return $return;
330   }
331
332   /**
333    * returns the URLS for the google map Javascript file
334    * @return string $js_url
335    */
336   public function getGoogleJsUrl()
337   {
338
339     return 'http://www.google.com/jsapi?key='.$this->getAPIKey();
340   }
341
342   /**
343    * Adds an icon to be loaded
344    * @param GMapIcon $icon A google Map Icon
345    */
346   public function addIcon($icon)
347   {
348     $this->icons[$icon->getName()]=$icon;
349   }
350  
351   /**
352    * Retourne l'objet GMapIcon à partir du nom de l'icone
353    *
354    * @param string $name
355    * @return GMapIcon
356    *
357    * @author Vincent
358    * @since 2008-12-02
359    */
360   public function getIconByName($name)
361   {
362     
363     return $this->icons[$name];
364   }
365  
366   /**
367    * @param GMapMarker $marker a marker to be put on the map
368    */
369   public function addMarker($marker)
370   {
371     array_push($this->markers,$marker);
372   }
373   /**
374    * @param GMapMarker[] $markers marker to be put on the map
375    */
376   public function setMarkers($markers)
377   {
378     $this->markers = $markers;
379   }
380   /**
381    * @param GMapEvent $event an event to be attached to the map
382    */
383   public function addEvent($event)
384   {
385     array_push($this->events,$event);
386   }
387
388   public function loadMarkerIcons()
389   {
390     foreach($this->markers as $marker)
391     {
392       if ($marker->getIcon() instanceof GMapIcon)
393       {
394         $this->addIcon($marker->getIcon());
395       }
396     }
397   }
398   /**
399    * Returns the javascript string which defines the icons
400    * @return string
401    */
402   public function getIconsJs()
403   {
404     $return = '';
405     foreach ($this->icons as $icon)
406     {
407       $return .= $icon->getIconJs();
408     }
409
410     return $return;
411   }
412   /**
413    * Returns the javascript string which defines the markers
414    * @return string
415    */
416   public function getMarkersJs()
417   {
418     $return = '';
419     foreach ($this->markers as $marker)
420     {
421       $return .= $marker->getMarkerJs();
422       $return .= $this->getJsName().'.addOverlay('.$marker->getName().');';
423       $return .= "\n      ";
424     }
425
426     return $return;
427   }
428
429   /*
430    * Returns the javascript string which defines events linked to the map
431    * @return string
432    */
433   public function getEventsJs()
434   {
435     $return = '';
436     foreach ($this->events as $event)
437     {
438       $return .= $event->getEventJs($this->getJsName());
439       $return .= "\n";
440     }
441     return $return;
442   }
443
444   /*
445    * Gets the Code to execute after Js initialization
446    * @return string $after_init_js
447    */
448   public function getAfterInitJs()
449   {
450     return $this->after_init_js;
451   }
452   /*
453    * Sets the Code to execute after Js initialization
454    * @param string $after_init_js Code to execute
455    */
456   public function addAfterInitJs($after_init_js)
457   {
458     array_push($this->after_init_js,$after_init_js);
459   }
460
461   public function addGlobalVariable($name, $value='null')
462   {
463     $this->global_variables[$name]=$value;
464
465   }
466   public function setZoom($zoom)
467   {
468     $this->zoom = $zoom;
469   }
470   /**
471    * Sets the center of the map at the beginning
472    *
473    * @param float $lat
474    * @param float $lng
475    */
476   public function setCenter($lat=null,$lng=null)
477   {
478     $this->center_coord = new GMapCoord($lat, $lng);
479   }
480  
481   /**
482    *
483    * @return GMapCoord
484    * @author fabriceb
485    * @since 2009-05-02
486    */
487   public function getCenterCoord()
488   {
489
490     return $this->center_coord;
491   }
492    /**
493    *
494    * @return float
495    * @author fabriceb
496    * @since 2009-05-02
497    */
498   public function getCenterLat()
499   {
500
501     return $this->getCenterCoord()->getLatitude();
502   }
503     /**
504    *
505    * @return float
506    * @author fabriceb
507    * @since 2009-05-02
508    */
509   public function getCenterLng()
510   {
511     return $this->getCenterCoord()->getLongitude();
512   }
513   public function getZoom()
514   {
515
516     return $this->zoom;
517   }
518  
519   /**
520    * gets the width of the map in pixels according to container style
521    * @return integer
522    * @author fabriceb
523    * @since 2009-05-03
524    */
525   public function getWidth()
526   {
527  
528     return intval(substr($this->getContainerStyle('width'),0,-2));
529   }
530  
531   /**
532    * gets the width of the map in pixels according to container style
533    * @return integer
534    * @author fabriceb
535    * @since 2009-05-03
536    */
537   public function getHeight()
538   {
539  
540     return intval(substr($this->getContainerStyle('height'),0,-2));
541   }
542  
543   /**
544    * sets the width of the map in pixels
545    *
546    * @param integer
547    * @author fabriceb
548    * @since 2009-05-03
549    */
550   public function setWidth($width)
551   {
552     $this->setContainerStyle('width',$width.'px');
553   }
554  
555   /**
556    * sets the width of the map in pixels
557    *
558    * @param integer
559    * @author fabriceb
560    * @since 2009-05-03
561    */
562   public function setHeight($height)
563   {
564     $this->setContainerStyle('height',$height.'px');
565   }
566  
567
568   /**
569    * Returns the URL of a static version of the map (when JavaScript is not active)
570    * Supports only markers and basic parameters: center, zoom, size.
571    * @param string $map_type = 'mobile'
572    * @param string $hl Language (fr, en...)
573    * @return string URL of the image
574    * @author Laurent Bachelier
575    */
576   public function getStaticMapUrl($maptype='mobile', $hl='fr')
577   {
578     $params = array(
579       'maptype' => $maptype,
580       'zoom'    => $this->getZoom(),
581       'key'     => $this->getAPIKey(),
582       'center'  => $this->getCenterLat().','.$this->getCenterLng(),
583       'size'    => $this->getWidth().'x'.$this->getHeight(),
584       'hl'      => $hl,
585       'markers' => $this->getMarkersStatic()
586     );
587     $pairs = array();
588     foreach($params as $key => $value)
589     {
590       $pairs[] = $key.'='.$value;
591     }
592
593     return 'http://maps.google.com/staticmap?'.implode('&',$pairs);
594   }
595
596   /**
597    * Returns the static code to create markers
598    * @return string
599    * @author Laurent Bachelier
600    */
601   protected function getMarkersStatic()
602   {
603     $markers_code = array();
604     foreach ($this->markers as $marker)
605     {
606       $markers_code[] = $marker->getMarkerStatic();
607     }
608
609     return implode('|',$markers_code);
610   }
611  
612   /**
613    *
614    * calculates the center of the markers linked to the map
615    *
616    * @return GMapCoord
617    * @author fabriceb
618    * @since 2009-05-02
619    */
620   public function getMarkersCenterCoord()
621   {
622     
623     return GMapMarker::getCenterCoord($this->markers);
624   }
625  
626   /**
627    * sets the center of the map at the center of the markers
628    *
629    * @author fabriceb
630    * @since 2009-05-02
631    */
632   public function centerOnMarkers()
633   {
634     $center = $this->getMarkersCenterCoord();
635  
636     $this->setCenter($center->getLatitude(), $center->getLongitude());
637   }
638  
639   /**
640    *
641    * calculates the zoom which fits the markers on the map
642    *
643    * @param integer $margin a scaling factor around the smallest bound
644    * @return integer $zoom
645    * @author fabriceb
646    * @since 2009-05-02
647    */
648   public function getMarkersFittingZoom($margin = 0)
649   {
650     // only one marker ? use a nice default zoom : 14
651     if (count($this->markers) < 2)
652     {
653       
654       return 14;
655     }
656     
657     $bounds = GMapBounds::getBoundsContainingMarkers($this->markers, $margin);
658     
659     return $bounds->getZoom(min($this->getWidth(),$this->getHeight()));
660   }
661  
662   /**
663    * sets the zoom of the map to fit the markers (uses mercator projection to guess the size in pixels of the bounds)
664    * WARNING : this depends on the width in pixels of the resulting map
665    *
666    * @param integer $margin a scaling factor around the smallest bound
667    * @author fabriceb
668    * @since 2009-05-02
669    */
670   public function zoomOnMarkers($margin = 0)
671   {
672     $this->setZoom($this->getMarkersFittingZoom($margin));
673   }
674
675    /**
676    * sets the zoom and center of the map to fit the markers (uses mercator projection to guess the size in pixels of the bounds)
677    *
678    * @param integer $margin a scaling factor around the smallest bound
679    * @author fabriceb
680    * @since 2009-05-02
681    */
682   public function centerAndZoomOnMarkers($margin = 0)
683   {
684     $this->centerOnMarkers();
685     $this->zoomOnMarkers($margin);
686   }
687  
688   /**
689    *
690    * @return GMapBounds
691    * @author fabriceb
692    * @since Jun 2, 2009 fabriceb
693    */
694   public function getBoundsFromCenterAndZoom()
695   {
696  
697     return GMapBounds::getBoundsFromCenterAndZoom($this->getCenterCoord(),$this->getZoom(),$this->getWidth(),$this->getHeight());
698   }
699
700 }
701
Note: See TracBrowser for help on using the browser.