Cuarto parche ->no funcional<- de implementación de Ajax con jQuery en ver+ubicaciones.
[ecomupi.git] / include / maps / GoogleMapAPI.class.php
blob63dc0b568075a360d53a194e34f7509415e8b950
1 <?php
2 error_reporting(E_STRICT | E_ALL);
4 /**
5 * Project: GoogleMapAPI: a PHP library inteface to the Google Map API
6 * File: GoogleMapAPI.class.php
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * For questions, help, comments, discussion, etc., please join the
23 * Smarty mailing list. Send a blank e-mail to
24 * smarty-general-subscribe@lists.php.net
26 * @link http://www.phpinsider.com/php/code/GoogleMapAPI/
27 * @copyright 2005 New Digital Group, Inc.
28 * @author Monte Ohrt <monte at ohrt dot com>
29 * @package GoogleMapAPI
30 * @version 2.5
33 /* $Id: GoogleMapAPI.class.php,v 1.63 2007/08/03 16:29:40 mohrt Exp $ */
37 For best results with GoogleMaps, use XHTML compliant web pages with this header:
39 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
40 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
42 For database caching, you will want to use this schema:
44 CREATE TABLE GEOCODES (
45 address varchar(255) NOT NULL default '',
46 lon float default NULL,
47 lat float default NULL,
48 PRIMARY KEY (address)
53 class GoogleMapAPI {
55 /**
56 * PEAR::DB DSN for geocode caching. example:
57 * $dsn = 'mysql://user:pass@localhost/dbname';
59 * @var string
61 var $dsn = null;
63 /**
64 * YOUR GooglMap API KEY for your site.
65 * (http://maps.google.com/apis/maps/signup.html)
67 * @var string
69 var $api_key = '';
71 /**
72 * current map id, set when you instantiate
73 * the GoogleMapAPI object.
75 * @var string
77 var $map_id = null;
79 /**
80 * sidebar <div> used along with this map.
82 * @var string
84 var $sidebar_id = NULL;
86 /**
87 * GoogleMapAPI uses the Yahoo geocode lookup API.
88 * This is the application ID for YOUR application.
89 * This is set upon instantiating the GoogleMapAPI object.
90 * (http://developer.yahoo.net/faq/index.html#appid)
92 * @var string
94 var $app_id = null;
96 /**
97 * use onLoad() to load the map javascript.
98 * if enabled, be sure to include on your webpage:
99 * <html onload="onLoad()">
101 * @var string
103 var $onload = true;
106 * map center latitude (horizontal)
107 * calculated automatically as markers
108 * are added to the map.
110 * @var float
112 var $center_lat = null;
115 * map center longitude (vertical)
116 * calculated automatically as markers
117 * are added to the map.
119 * @var float
121 var $center_lon = null;
124 * enables map controls (zoom/move/center)
126 * @var boolean
128 var $map_controls = true;
131 * determines the map control type
132 * small -> show move/center controls
133 * large -> show move/center/zoom controls
135 * @var string
137 var $control_size = 'large';
140 * enables map type controls (map/satellite/hybrid)
142 * @var boolean
144 var $type_controls = true;
147 * default map type (G_NORMAL_MAP/G_SATELLITE_MAP/G_HYBRID_MAP)
149 * @var boolean
151 var $map_type = 'G_NORMAL_MAP';
154 * enables scale map control
156 * @var boolean
158 var $scale_control = true;
161 * enables overview map control
163 * @var boolean
165 var $overview_control = false;
168 * determines the default zoom level
170 * @var integer
172 var $zoom = 16;
175 * determines the map width
177 * @var integer
179 var $width = '500px';
182 * determines the map height
184 * @var integer
186 var $height = '500px';
189 * message that pops up when the browser is incompatible with Google Maps.
190 * set to empty string to disable.
192 * @var integer
194 var $browser_alert = 'Sorry, the Google Maps API is not compatible with this browser.';
197 * message that appears when javascript is disabled.
198 * set to empty string to disable.
200 * @var string
202 var $js_alert = '<b>Javascript must be enabled in order to use Google Maps.</b>';
205 * determines if sidebar is enabled
207 * @var boolean
209 var $sidebar = true;
212 * determines if to/from directions are included inside info window
214 * @var boolean
216 var $directions = true;
219 * determines if map markers bring up an info window
221 * @var boolean
223 var $info_window = true;
226 * determines if info window appears with a click or mouseover
228 * @var string click/mouseover
230 var $window_trigger = 'click';
233 * what server geocode lookups come from
235 * available: YAHOO Yahoo! API. US geocode lookups only.
236 * GOOGLE Google Maps. This can do international lookups,
237 * but not an official API service so no guarantees.
238 * Note: GOOGLE is the default lookup service, please read
239 * the Yahoo! terms of service before using their API.
241 * @var string service name
243 var $lookup_service = 'GOOGLE';
244 var $lookup_server = array('GOOGLE' => 'maps.google.com', 'YAHOO' => 'api.local.yahoo.com');
247 * version number
249 * @var string
251 var $_version = '2.5';
254 * list of added markers
256 * @var array
258 var $_markers = array();
261 * maximum longitude of all markers
263 * @var float
265 var $_max_lon = -1000000;
268 * minimum longitude of all markers
270 * @var float
272 var $_min_lon = 1000000;
275 * max latitude
277 * @var float
279 var $_max_lat = -1000000;
282 * min latitude
284 * @var float
286 var $_min_lat = 1000000;
289 * determines if we should zoom to minimum level (above this->zoom value) that will encompass all markers
291 * @var boolean
293 var $zoom_encompass = true;
296 * factor by which to fudge the boundaries so that when we zoom encompass, the markers aren't too close to the edge
298 * @var float
300 var $bounds_fudge = 0.01;
303 * use the first suggestion by a google lookup if exact match not found
305 * @var float
307 var $use_suggest = false;
311 * list of added polylines
313 * @var array
315 var $_polylines = array();
318 * icon info array
320 * @var array
322 var $_icons = array();
325 * database cache table name
327 * @var string
329 var $_db_cache_table = 'GEOCODES';
333 * class constructor
335 * @param string $map_id the id for this map
336 * @param string $app_id YOUR Yahoo App ID
338 function GoogleMapAPI($map_id = 'map', $app_id = 'MyMapApp') {
339 $this->map_id = $map_id;
340 $this->sidebar_id = 'sidebar_' . $map_id;
341 $this->app_id = $app_id;
345 * sets the PEAR::DB dsn
347 * @param string $dsn
349 function setDSN($dsn) {
350 $this->dsn = $dsn;
354 * sets YOUR Google Map API key
356 * @param string $key
358 function setAPIKey($key) {
359 $this->api_key = $key;
363 * sets the width of the map
365 * @param string $width
367 function setWidth($width) {
368 if(!preg_match('!^(\d+)(.*)$!',$width,$_match))
369 return false;
371 $_width = $_match[1];
372 $_type = $_match[2];
373 if($_type == '%')
374 $this->width = $_width . '%';
375 else
376 $this->width = $_width . 'px';
378 return true;
382 * sets the height of the map
384 * @param string $height
386 function setHeight($height) {
387 if(!preg_match('!^(\d+)(.*)$!',$height,$_match))
388 return false;
390 $_height = $_match[1];
391 $_type = $_match[2];
392 if($_type == '%')
393 $this->height = $_height . '%';
394 else
395 $this->height = $_height . 'px';
397 return true;
401 * sets the default map zoom level
403 * @param string $level
405 function setZoomLevel($level) {
406 $this->zoom = (int) $level;
410 * enables the map controls (zoom/move)
413 function enableMapControls() {
414 $this->map_controls = true;
418 * disables the map controls (zoom/move)
421 function disableMapControls() {
422 $this->map_controls = false;
426 * sets the map control size (large/small)
428 * @param string $size
430 function setControlSize($size) {
431 if(in_array($size,array('large','small')))
432 $this->control_size = $size;
436 * enables the type controls (map/satellite/hybrid)
439 function enableTypeControls() {
440 $this->type_controls = true;
444 * disables the type controls (map/satellite/hybrid)
447 function disableTypeControls() {
448 $this->type_controls = false;
452 * set default map type (map/satellite/hybrid)
455 function setMapType($type) {
456 switch($type) {
457 case 'hybrid':
458 $this->map_type = 'G_HYBRID_MAP';
459 break;
460 case 'satellite':
461 $this->map_type = 'G_SATELLITE_MAP';
462 break;
463 case 'map':
464 default:
465 $this->map_type = 'G_NORMAL_MAP';
466 break;
471 * enables onload
474 function enableOnLoad() {
475 $this->onload = true;
479 * disables onload
482 function disableOnLoad() {
483 $this->onload = false;
487 * enables sidebar
490 function enableSidebar() {
491 $this->sidebar = true;
495 * disables sidebar
498 function disableSidebar() {
499 $this->sidebar = false;
503 * enables map directions inside info window
506 function enableDirections() {
507 $this->directions = true;
511 * disables map directions inside info window
514 function disableDirections() {
515 $this->directions = false;
519 * set browser alert message for incompatible browsers
521 * @params $message string
523 function setBrowserAlert($message) {
524 $this->browser_alert = $message;
528 * set <noscript> message when javascript is disabled
530 * @params $message string
532 function setJSAlert($message) {
533 $this->js_alert = $message;
537 * enable map marker info windows
539 function enableInfoWindow() {
540 $this->info_window = true;
544 * disable map marker info windows
546 function disableInfoWindow() {
547 $this->info_window = false;
551 * set the info window trigger action
553 * @params $message string click/mouseover
555 function setInfoWindowTrigger($type) {
556 switch($type) {
557 case 'mouseover':
558 $this->window_trigger = 'mouseover';
559 break;
560 default:
561 $this->window_trigger = 'click';
562 break;
567 * enable zoom to encompass makers
569 function enableZoomEncompass() {
570 $this->zoom_encompass = true;
574 * disable zoom to encompass makers
576 function disableZoomEncompass() {
577 $this->zoom_encompass = false;
581 * set the boundary fudge factor
583 function setBoundsFudge($val) {
584 $this->bounds_fudge = $val;
588 * enables the scale map control
591 function enableScaleControl() {
592 $this->scale_control = true;
596 * disables the scale map control
599 function disableScaleControl() {
600 $this->scale_control = false;
604 * enables the overview map control
607 function enableOverviewControl() {
608 $this->overview_control = true;
612 * disables the overview map control
615 function disableOverviewControl() {
616 $this->overview_control = false;
621 * set the lookup service to use for geocode lookups
622 * default is YAHOO, you can also use GOOGLE.
623 * NOTE: GOOGLE can to intl lookups, but is not an
624 * official API, so use at your own risk.
627 function setLookupService($service) {
628 switch($service) {
629 case 'GOOGLE':
630 $this->lookup_service = 'GOOGLE';
631 break;
632 case 'YAHOO':
633 default:
634 $this->lookup_service = 'YAHOO';
635 break;
641 * adds a map marker by address
643 * @param string $address the map address to mark (street/city/state/zip)
644 * @param string $title the title display in the sidebar
645 * @param string $html the HTML block to display in the info bubble (if empty, title is used)
647 function addMarkerByAddress($address,$title = '',$html = '',$tooltip = '',$id = '') {
648 if(($_geocode = $this->getGeocode($address)) === false)
649 return false;
650 return $this->addMarkerByCoords($_geocode['lon'],$_geocode['lat'],$title,$html,$tooltip);
654 * adds a map marker by geocode
656 * @param string $lon the map longitude (horizontal)
657 * @param string $lat the map latitude (vertical)
658 * @param string $title the title display in the sidebar
659 * @param string $html|array $html
660 * string: the HTML block to display in the info bubble (if empty, title is used)
661 * array: The title => content pairs for a tabbed info bubble
663 // TODO make it so you can specify which tab you want the directions to appear in (add another arg)
664 function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '',$id = '') {
665 $_marker['lon'] = $lon;
666 $_marker['lat'] = $lat;
667 $_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
668 $_marker['title'] = $title;
669 $_marker['tooltip'] = $tooltip;
670 $_marker['id'] = $id;
671 $this->_markers[] = $_marker;
672 $this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
673 // return index of marker
674 // HACK
675 return count($this->_markers) - 1;
676 // HACK
679 // HACK
680 function deleteMarkers() {
681 unset ($this->_markers);
682 return;
685 * adds a map polyline by address
686 * if color, weight and opacity are not defined, use the google maps defaults
688 * @param string $address1 the map address to draw from
689 * @param string $address2 the map address to draw to
690 * @param string $color the color of the line (format: #000000)
691 * @param string $weight the weight of the line in pixels
692 * @param string $opacity the line opacity (percentage)
694 function addPolyLineByAddress($address1,$address2,$color='',$weight=0,$opacity=0) {
695 if(($_geocode1 = $this->getGeocode($address1)) === false)
696 return false;
697 if(($_geocode2 = $this->getGeocode($address2)) === false)
698 return false;
699 return $this->addPolyLineByCoords($_geocode1['lon'],$_geocode1['lat'],$_geocode2['lon'],$_geocode2['lat'],$color,$weight,$opacity);
703 * adds a map polyline by map coordinates
704 * if color, weight and opacity are not defined, use the google maps defaults
706 * @param string $lon1 the map longitude to draw from
707 * @param string $lat1 the map latitude to draw from
708 * @param string $lon2 the map longitude to draw to
709 * @param string $lat2 the map latitude to draw to
710 * @param string $color the color of the line (format: #000000)
711 * @param string $weight the weight of the line in pixels
712 * @param string $opacity the line opacity (percentage)
714 function addPolyLineByCoords($lon1,$lat1,$lon2,$lat2,$color='',$weight=0,$opacity=0) {
715 $_polyline['lon1'] = $lon1;
716 $_polyline['lat1'] = $lat1;
717 $_polyline['lon2'] = $lon2;
718 $_polyline['lat2'] = $lat2;
719 $_polyline['color'] = $color;
720 $_polyline['weight'] = $weight;
721 $_polyline['opacity'] = $opacity;
722 $this->_polylines[] = $_polyline;
723 $this->adjustCenterCoords($_polyline['lon1'],$_polyline['lat1']);
724 $this->adjustCenterCoords($_polyline['lon2'],$_polyline['lat2']);
725 // return index of polyline
726 return count($this->_polylines) - 1;
730 * adjust map center coordinates by the given lat/lon point
732 * @param string $lon the map latitude (horizontal)
733 * @param string $lat the map latitude (vertical)
735 function adjustCenterCoords($lon,$lat) {
736 if(strlen((string)$lon) == 0 || strlen((string)$lat) == 0)
737 return false;
738 $this->_max_lon = (float) max($lon, $this->_max_lon);
739 $this->_min_lon = (float) min($lon, $this->_min_lon);
740 $this->_max_lat = (float) max($lat, $this->_max_lat);
741 $this->_min_lat = (float) min($lat, $this->_min_lat);
743 $this->center_lon = (float) ($this->_min_lon + $this->_max_lon) / 2;
744 $this->center_lat = (float) ($this->_min_lat + $this->_max_lat) / 2;
745 return true;
749 * set map center coordinates to lat/lon point
751 * @param string $lon the map latitude (horizontal)
752 * @param string $lat the map latitude (vertical)
754 function setCenterCoords($lon,$lat) {
755 $this->center_lat = (float) $lat;
756 $this->center_lon = (float) $lon;
760 * generate an array of params for a new marker icon image
761 * iconShadowImage is optional
762 * If anchor coords are not supplied, we use the center point of the image by default.
763 * Can be called statically. For private use by addMarkerIcon() and setMarkerIcon()
765 * @param string $iconImage URL to icon image
766 * @param string $iconShadowImage URL to shadow image
767 * @param string $iconAnchorX X coordinate for icon anchor point
768 * @param string $iconAnchorY Y coordinate for icon anchor point
769 * @param string $infoWindowAnchorX X coordinate for info window anchor point
770 * @param string $infoWindowAnchorY Y coordinate for info window anchor point
772 function createMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
773 $_icon_image_path = $iconImage;
774 if(!($_image_info = @getimagesize($_icon_image_path))) {
775 die('GoogleMapAPI:createMarkerIcon: Error reading image [1]: ' . $iconImage);
777 if($iconShadowImage) {
778 $_shadow_image_path = $iconShadowImage;
779 if(!($_shadow_info = @getimagesize($_shadow_image_path))) {
780 die('GoogleMapAPI:createMarkerIcon: Error reading image [2]: ' . $iconShadowImage);
784 if($iconAnchorX === 'x') {
785 $iconAnchorX = (int) ($_image_info[0] / 2);
787 if($iconAnchorY === 'x') {
788 $iconAnchorY = (int) ($_image_info[1] / 2);
790 if($infoWindowAnchorX === 'x') {
791 $infoWindowAnchorX = (int) ($_image_info[0] / 2);
793 if($infoWindowAnchorY === 'x') {
794 $infoWindowAnchorY = (int) ($_image_info[1] / 2);
797 $icon_info = array(
798 'image' => $iconImage,
799 'iconWidth' => $_image_info[0],
800 'iconHeight' => $_image_info[1],
801 'iconAnchorX' => $iconAnchorX,
802 'iconAnchorY' => $iconAnchorY,
803 'infoWindowAnchorX' => $infoWindowAnchorX,
804 'infoWindowAnchorY' => $infoWindowAnchorY
806 if($iconShadowImage) {
807 $icon_info = array_merge($icon_info, array('shadow' => $iconShadowImage,
808 'shadowWidth' => $_shadow_info[0],
809 'shadowHeight' => $_shadow_info[1]));
811 return $icon_info;
815 * set the marker icon for ALL markers on the map
817 function setMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
818 $this->_icons = array($this->createMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY));
822 * add an icon to go with the correspondingly added marker
824 function addMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
825 $this->_icons[] = $this->createMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY);
826 return count($this->_icons) - 1;
831 * print map javascript (put just before </body>, or in <header> if using onLoad())
834 function printMapJS() {
835 echo $this->getMapJS();
839 * return map javascript
842 function getMapJS() {
843 $_output = '<script type="text/javascript" charset="utf-8">' . "\n";
844 $_output .= '//<![CDATA[' . "\n";
845 $_output .= "/*************************************************\n";
846 $_output .= " * Created with GoogleMapAPI " . $this->_version . "\n";
847 $_output .= " * Author: Monte Ohrt <monte AT ohrt DOT com>\n";
848 $_output .= " * Copyright 2005-2006 New Digital Group\n";
849 $_output .= " * http://www.phpinsider.com/php/code/GoogleMapAPI/\n";
850 $_output .= " *************************************************/\n";
852 $_output .= 'var points = [];' . "\n";
853 $_output .= 'var markers = [];' . "\n";
854 $_output .= 'var counter = 0;' . "\n";
855 if($this->sidebar) {
856 $_output .= 'var sidebar_html = "";' . "\n";
857 $_output .= 'var marker_html = [];' . "\n";
860 if($this->directions) {
861 $_output .= 'var to_htmls = [];' . "\n";
862 $_output .= 'var from_htmls = [];' . "\n";
865 if(!empty($this->_icons)) {
866 $_output .= 'var icon = [];' . "\n";
867 for($i = 0, $j = count($this->_icons); $i<$j; $i++) {
868 $info = $this->_icons[$i];
870 // hash the icon data to see if we've already got this one; if so, save some javascript
871 $icon_key = md5(serialize($info));
872 if(!isset($exist_icn[$icon_key])) {
874 $_output .= "icon[$i] = new GIcon();\n";
875 $_output .= sprintf('icon[%s].image = "%s";',$i,$info['image']) . "\n";
876 if($info['shadow']) {
877 $_output .= sprintf('icon[%s].shadow = "%s";',$i,$info['shadow']) . "\n";
878 $_output .= sprintf('icon[%s].shadowSize = new GSize(%s,%s);',$i,$info['shadowWidth'],$info['shadowHeight']) . "\n";
880 $_output .= sprintf('icon[%s].iconSize = new GSize(%s,%s);',$i,$info['iconWidth'],$info['iconHeight']) . "\n";
881 $_output .= sprintf('icon[%s].iconAnchor = new GPoint(%s,%s);',$i,$info['iconAnchorX'],$info['iconAnchorY']) . "\n";
882 $_output .= sprintf('icon[%s].infoWindowAnchor = new GPoint(%s,%s);',$i,$info['infoWindowAnchorX'],$info['infoWindowAnchorY']) . "\n";
883 } else {
884 $_output .= "icon[$i] = icon[$exist_icn[$icon_key]];\n";
889 $_output .= 'var map = null;' . "\n";
891 if($this->onload) {
892 $_output .= 'function onLoad() {' . "\n";
895 if(!empty($this->browser_alert)) {
896 $_output .= 'if (GBrowserIsCompatible()) {' . "\n";
899 $_output .= sprintf('var mapObj = document.getElementById("%s");',$this->map_id) . "\n";
900 $_output .= 'if (mapObj != "undefined" && mapObj != null) {' . "\n";
901 $_output .= sprintf('map = new GMap2(document.getElementById("%s"));',$this->map_id) . "\n";
902 if(isset($this->center_lat) && isset($this->center_lon)) {
903 // Special care for decimal point in lon and lat, would get lost if "wrong" locale is set; applies to (s)printf only
904 $_output .= sprintf('map.setCenter(new GLatLng(%s, %s), %d, %s);', number_format($this->center_lat, 6, ".", ""), number_format($this->center_lon, 6, ".", ""), $this->zoom, $this->map_type) . "\n";
907 // zoom so that all markers are in the viewport
908 if($this->zoom_encompass && count($this->_markers) > 1) {
909 // increase bounds by fudge factor to keep
910 // markers away from the edges
911 $_len_lon = $this->_max_lon - $this->_min_lon;
912 $_len_lat = $this->_max_lat - $this->_min_lat;
913 $this->_min_lon -= $_len_lon * $this->bounds_fudge;
914 $this->_max_lon += $_len_lon * $this->bounds_fudge;
915 $this->_min_lat -= $_len_lat * $this->bounds_fudge;
916 $this->_max_lat += $_len_lat * $this->bounds_fudge;
918 $_output .= "var bds = new GLatLngBounds(new GLatLng($this->_min_lat, $this->_min_lon), new GLatLng($this->_max_lat, $this->_max_lon));\n";
919 $_output .= 'map.setZoom(map.getBoundsZoomLevel(bds));' . "\n";
922 if($this->map_controls) {
923 if($this->control_size == 'large')
924 $_output .= 'map.addControl(new GLargeMapControl());' . "\n";
925 else
926 $_output .= 'map.addControl(new GSmallMapControl());' . "\n";
928 if($this->type_controls) {
929 $_output .= 'map.addControl(new GMapTypeControl());' . "\n";
932 if($this->scale_control) {
933 $_output .= 'map.addControl(new GScaleControl());' . "\n";
936 if($this->overview_control) {
937 $_output .= 'map.addControl(new GOverviewMapControl());' . "\n";
940 $_output .= $this->getAddMarkersJS();
942 $_output .= $this->getPolylineJS();
944 if($this->sidebar) {
945 // HACK HACK
946 //$_output .= sprintf('document.getElementById("%s").innerHTML = "<ul class=\"gmapSidebar\">"+ sidebar_html +"<\/ul>";', $this->sidebar_id) . "\n";
947 $_output .= sprintf('document.getElementById("%s").innerHTML = "Ver Eco Mupis:<br /><select class=\"gmapSidebar\">"+ sidebar_html +"</select>";', 'lista_mupis') . "\n";
950 $_output .= '}' . "\n";
952 if(!empty($this->browser_alert)) {
953 $_output .= '} else {' . "\n";
954 $_output .= 'alert("' . str_replace('"','\"',$this->browser_alert) . '");' . "\n";
955 $_output .= '}' . "\n";
958 if($this->onload) {
959 $_output .= '}' . "\n";
962 $_output .= $this->getCreateMarkerJS();
964 // Utility functions used to distinguish between tabbed and non-tabbed info windows
965 $_output .= 'function isArray(a) {return isObject(a) && a.constructor == Array;}' . "\n";
966 $_output .= 'function isObject(a) {return (a && typeof a == \'object\') || isFunction(a);}' . "\n";
967 $_output .= 'function isFunction(a) {return typeof a == \'function\';}' . "\n";
969 if($this->sidebar) {
970 $_output .= 'function click_sidebar(idx) {' . "\n";
971 // HACK //
972 $_output .= " var titulo = document.getElementById('gmapSidebarItem_' + idx).innerHTML;\n";
973 $_output .= ' document.getElementById(\'datos_mupis\').firstChild.nodeValue = loadXMLDoc(\'contenido/mupis+ubicaciones+dinamico.php?accion=mupi&amp;MUPI=\'+titulo)' . "\n";
974 // HACK //
975 $_output .= ' if(isArray(marker_html[idx])) { markers[idx].openInfoWindowTabsHtml(marker_html[idx]); }' . "\n";
976 $_output .= ' else { markers[idx].openInfoWindowHtml(marker_html[idx]); }' . "\n";
977 $_output .= '}' . "\n";
979 $_output .= 'function showInfoWindow(idx,html) {' . "\n";
980 $_output .= 'map.centerAtLatLng(points[idx]);' . "\n";
981 $_output .= 'markers[idx].openInfoWindowHtml(html);' . "\n";
982 $_output .= '}' . "\n";
983 if($this->directions) {
984 $_output .= 'function tohere(idx) {' . "\n";
985 $_output .= 'markers[idx].openInfoWindowHtml(to_htmls[idx]);' . "\n";
986 $_output .= '}' . "\n";
987 $_output .= 'function fromhere(idx) {' . "\n";
988 $_output .= 'markers[idx].openInfoWindowHtml(from_htmls[idx]);' . "\n";
989 $_output .= '}' . "\n";
992 $_output .= '//]]>' . "\n";
993 $_output .= '</script>' . "\n";
994 return $_output;
998 * overridable function for generating js to add markers
1000 function getAddMarkersJS() {
1001 $SINGLE_TAB_WIDTH = 88; // constant: width in pixels of each tab heading (set by google)
1002 $i = 0;
1003 $_output = '';
1004 foreach($this->_markers as $_marker) {
1005 if(is_array($_marker['html'])) {
1006 // warning: you can't have two tabs with the same header. but why would you want to?
1007 $ti = 0;
1008 $num_tabs = count($_marker['html']);
1009 $tab_obs = array();
1010 foreach($_marker['html'] as $tab => $info) {
1011 if($ti == 0 && $num_tabs > 2) {
1012 $width_style = sprintf(' style=\"width: %spx\"', $num_tabs * $SINGLE_TAB_WIDTH);
1013 } else {
1014 $width_style = '';
1016 $tab = str_replace('"','\"',$tab);
1017 $info = str_replace('"','\"',$info);
1018 $info = str_replace(array("\n", "\r"), "", $info);
1019 $tab_obs[] = sprintf('new GInfoWindowTab("%s", "%s")', $tab, '<div id=\"gmapmarker\"'.$width_style.'>' . $info . '</div>');
1020 $ti++;
1022 $iw_html = '[' . join(',',$tab_obs) . ']';
1023 } else {
1024 $iw_html = sprintf('"%s"',str_replace('"','\"','<div id="gmapmarker">' . str_replace(array("\n", "\r"), "", $_marker['html']) . '</div>'));
1026 // HACK ID
1027 $_output .= sprintf('var point = new GLatLng(%s,%s);',$_marker['lat'],$_marker['lon']) . "\n";
1028 $_output .= sprintf('var marker = createMarker(point,"%s",%s, %s,"%s","%s");',
1029 str_replace('"','\"',$_marker['title']),
1030 str_replace('/','\/',$iw_html),
1032 str_replace('"','\"',$_marker['tooltip']),
1033 $_marker['id']) . "\n";
1034 //TODO: in above createMarker call, pass the index of the tab in which to put directions, if applicable
1035 $_output .= 'map.addOverlay(marker);' . "\n";
1036 $i++;
1038 return $_output;
1042 * overridable function to generate polyline js
1044 function getPolylineJS() {
1045 $_output = '';
1046 foreach($this->_polylines as $_polyline) {
1047 $_output .= sprintf('var polyline = new GPolyline([new GLatLng(%s,%s),new GLatLng(%s,%s)],"%s",%s,%s);',
1048 $_polyline['lat1'],$_polyline['lon1'],$_polyline['lat2'],$_polyline['lon2'],$_polyline['color'],$_polyline['weight'],$_polyline['opacity'] / 100.0) . "\n";
1049 $_output .= 'map.addOverlay(polyline);' . "\n";
1051 return $_output;
1055 * overridable function to generate the js for the js function for creating a marker.
1057 // IMPORTANTE!, acá tiene que ir el hack mayor!.
1058 function getCreateMarkerJS() {
1059 $_SCRIPT_ = '$("#datos_mupis").load(\'contenido/mupis+ubicaciones+dinamico.php?accion=mupi&MUPI=\'+id);';
1060 $_output = 'function createMarker(point, title, html, n, tooltip, id) {' . "\n";
1061 $_output .= 'if(n >= '. sizeof($this->_icons) .') { n = '. (sizeof($this->_icons) - 1) ."; }\n";
1062 if(!empty($this->_icons)) {
1063 $_output .= 'var marker = new GMarker(point,{\'icon\': icon[n], \'title\': tooltip});' . "\n";
1064 } else {
1065 $_output .= 'var marker = new GMarker(point,{\'title\': tooltip});' . "\n";
1067 if($this->directions) {
1068 $_output .= 'var tabFlag = isArray(html);' . "\n";
1069 $_output .= 'if(!tabFlag) { html = [{"contentElem": html}]; }' . "\n";
1070 $_output .= 'if(!tabFlag) { html = html[0].contentElem; }';
1073 if($this->info_window) {
1074 $_output .= sprintf('if(isArray(html)) { GEvent.addListener(marker, "%s", function() { marker.openInfoWindowTabsHtml(html); }); }',$this->window_trigger) . "\n";
1075 $_output .= sprintf('else { GEvent.addListener(marker, "%s", function() { marker.openInfoWindowHtml(html); '.$_SCRIPT_.' }); }',$this->window_trigger) . "\n";
1077 $_output .= 'points[counter] = point;' . "\n";
1078 $_output .= 'markers[counter] = marker;' . "\n";
1079 if($this->sidebar) {
1080 $_output .= 'marker_html[counter] = html;' . "\n";
1081 // HACK HACK
1082 //$_output .= "sidebar_html += '<li class=\"gmapSidebarItem\" id=\"gmapSidebarItem_'+ counter +'\"><a href=\"javascript:click_sidebar(' + counter + ')\">' + title + '<\/a><\/li>';" . "\n";
1083 $_output .= 'sidebar_html += \'<option class="gmapSidebarItem" id="gmapSidebarItem" value="\'+title+\'">\' + title + \'</option>\';' . "\n";
1085 $_output .= 'counter++;' . "\n";
1086 $_output .= 'return marker;' . "\n";
1087 $_output .= '}' . "\n";
1088 return $_output;
1092 * print map (put at location map will appear)
1095 function printMap() {
1096 echo $this->getMap();
1100 * return map
1103 function getMap() {
1104 $_output = '';
1105 if(strlen($this->width) > 0 && strlen($this->height) > 0) {
1106 $_output .= sprintf('<div id="%s" style="width: %s; height: %s"></div>',$this->map_id,$this->width,$this->height) . "\n";
1107 } else {
1108 $_output .= sprintf('<div id="%s"></div>;',$this->map_id) . "\n";
1110 return $_output;
1115 * print sidebar (put at location sidebar will appear)
1118 function printSidebar() {
1119 echo $this->getSidebar();
1123 * return sidebar html
1126 function getSidebar() {
1127 return sprintf('<div id="%s"></div>',$this->sidebar_id) . "\n";
1131 * get the geocode lat/lon points from given address
1132 * look in cache first, otherwise get from Yahoo
1134 * @param string $address
1136 function getGeocode($address) {
1137 if(empty($address))
1138 return false;
1140 $_geocode = false;
1142 if(($_geocode = $this->getCache($address)) === false) {
1143 if(($_geocode = $this->geoGetCoords($address)) !== false) {
1144 $this->putCache($address, $_geocode['lon'], $_geocode['lat']);
1148 return $_geocode;
1152 * get the geocode lat/lon points from cache for given address
1154 * @param string $address
1156 function getCache($address) {
1157 if(!isset($this->dsn))
1158 return false;
1160 $_ret = array();
1162 // PEAR DB
1163 require_once('DB.php');
1164 $_db =& DB::connect($this->dsn);
1165 if (PEAR::isError($_db)) {
1166 die($_db->getMessage());
1168 $_res =& $_db->query("SELECT lon,lat FROM {$this->_db_cache_table} where address = ?", $address);
1169 if (PEAR::isError($_res)) {
1170 die($_res->getMessage());
1172 if($_row = $_res->fetchRow()) {
1173 $_ret['lon'] = $_row[0];
1174 $_ret['lat'] = $_row[1];
1177 $_db->disconnect();
1179 return !empty($_ret) ? $_ret : false;
1183 * put the geocode lat/lon points into cache for given address
1185 * @param string $address
1186 * @param string $lon the map latitude (horizontal)
1187 * @param string $lat the map latitude (vertical)
1189 function putCache($address, $lon, $lat) {
1190 if(!isset($this->dsn) || (strlen($address) == 0 || strlen($lon) == 0 || strlen($lat) == 0))
1191 return false;
1192 // PEAR DB
1193 require_once('DB.php');
1194 $_db =& DB::connect($this->dsn);
1195 if (PEAR::isError($_db)) {
1196 die($_db->getMessage());
1199 $_res =& $_db->query('insert into '.$this->_db_cache_table.' values (?, ?, ?)', array($address, $lon, $lat));
1200 if (PEAR::isError($_res)) {
1201 die($_res->getMessage());
1203 $_db->disconnect();
1205 return true;
1210 * get geocode lat/lon points for given address from Yahoo
1212 * @param string $address
1214 function geoGetCoords($address,$depth=0) {
1216 switch($this->lookup_service) {
1218 case 'GOOGLE':
1220 $_url = sprintf('http://%s/maps/geo?&q=%s&output=csv&key=%s',$this->lookup_server['GOOGLE'],rawurlencode($address),$this->api_key);
1222 $_result = false;
1224 if($_result = $this->fetchURL($_url)) {
1226 $_result_parts = explode(',',$_result);
1227 if($_result_parts[0] != 200)
1228 return false;
1229 $_coords['lat'] = $_result_parts[2];
1230 $_coords['lon'] = $_result_parts[3];
1233 break;
1235 case 'YAHOO':
1236 default:
1238 $_url = 'http://%s/MapsService/V1/geocode';
1239 $_url .= sprintf('?appid=%s&location=%s',$this->lookup_server['YAHOO'],$this->app_id,rawurlencode($address));
1241 $_result = false;
1243 if($_result = $this->fetchURL($_url)) {
1245 preg_match('!<Latitude>(.*)</Latitude><Longitude>(.*)</Longitude>!U', $_result, $_match);
1247 $_coords['lon'] = $_match[2];
1248 $_coords['lat'] = $_match[1];
1252 break;
1255 return $_coords;
1261 * fetch a URL. Override this method to change the way URLs are fetched.
1263 * @param string $url
1265 function fetchURL($url) {
1267 return file_get_contents($url);
1272 * get distance between to geocoords using great circle distance formula
1274 * @param float $lat1
1275 * @param float $lat2
1276 * @param float $lon1
1277 * @param float $lon2
1278 * @param float $unit M=miles, K=kilometers, N=nautical miles, I=inches, F=feet
1280 function geoGetDistance($lat1,$lon1,$lat2,$lon2,$unit='K') {
1282 // calculate miles
1283 $M = 69.09 * rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2))));
1285 switch(strtoupper($unit))
1287 case 'K':
1288 // kilometers
1289 return $M * 1.609344;
1290 break;
1291 case 'N':
1292 // nautical miles
1293 return $M * 0.868976242;
1294 break;
1295 case 'F':
1296 // feet
1297 return $M * 5280;
1298 break;
1299 case 'I':
1300 // inches
1301 return $M * 63360;
1302 break;
1303 case 'M':
1304 default:
1305 // miles
1306 return $M;
1307 break;