commit masivo.
[ecomupi.git] / include / maps / GoogleMapAPI.class.php
blob1234d29279951f6ee7a2337bcb94715f98cade22
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
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 $ */
35 class GoogleMapAPI {
37 var $dsn = null;
38 var $api_key = '';
39 var $map_id = null;
40 var $sidebar_id = NULL;
41 var $app_id = null;
42 var $onload = true;
43 var $center_lat = null;
44 var $center_lon = null;
45 var $map_controls = true;
46 var $control_size = 'large';
47 var $type_controls = false;
48 var $map_type = 'G_NORMAL_MAP';
49 var $scale_control = false;
50 var $disable_map_drag = false;
51 var $disable_drag = false;
52 var $Mostrar_Contenido_Maximizado = true;
53 var $referencias = false;
54 var $overview_control = false;
55 var $zoom = 17;
56 var $width = '500px';
57 var $height = '500px';
58 var $sidebar = false;
59 var $info_window = true;
60 var $window_trigger = 'click';
61 var $lookup_service = 'GOOGLE';
62 var $lookup_server = array('GOOGLE' => 'maps.google.com', 'YAHOO' => 'api.local.yahoo.com');
63 var $_version = '2.5';
64 var $_markers = array();
65 var $_max_lon = -1000000;
66 var $_min_lon = 1000000;
67 var $_max_lat = -1000000;
68 var $_min_lat = 1000000;
69 var $zoom_encompass = false;
70 var $bounds_fudge = 0.01;
71 var $use_suggest = false;
72 var $_polylines = array();
73 var $_icons = array();
74 var $_db_cache_table = 'GEOCODES';
76 function GoogleMapAPI($map_id = 'map', $app_id = 'MyMapApp') {
77 $this->map_id = $map_id;
78 $this->sidebar_id = 'sidebar_' . $map_id;
79 $this->app_id = $app_id;
82 /**
83 * sets the PEAR::DB dsn
85 * @param string $dsn
87 function setDSN($dsn) {
88 $this->dsn = $dsn;
91 /**
92 * sets YOUR Google Map API key
94 * @param string $key
96 function setAPIKey($key) {
97 $this->api_key = $key;
101 * sets the width of the map
103 * @param string $width
105 function setWidth($width) {
106 if(!preg_match('!^(\d+)(.*)$!',$width,$_match))
107 return false;
109 $_width = $_match[1];
110 $_type = $_match[2];
111 if($_type == '%')
112 $this->width = $_width . '%';
113 else
114 $this->width = $_width . 'px';
116 return true;
120 * sets the height of the map
122 * @param string $height
124 function setHeight($height) {
125 if(!preg_match('!^(\d+)(.*)$!',$height,$_match))
126 return false;
128 $_height = $_match[1];
129 $_type = $_match[2];
130 if($_type == '%')
131 $this->height = $_height . '%';
132 else
133 $this->height = $_height . 'px';
135 return true;
139 * sets the default map zoom level
141 * @param string $level
143 function setZoomLevel($level) {
144 $this->zoom = (int) $level;
148 * enables the map controls (zoom/move)
151 function enableMapControls() {
152 $this->map_controls = true;
156 * disables the map controls (zoom/move)
159 function disableMapControls() {
160 $this->map_controls = false;
164 * sets the map control size (large/small)
166 * @param string $size
168 function setControlSize($size) {
169 if(in_array($size,array('large','small')))
170 $this->control_size = $size;
174 * enables the type controls (map/satellite/hybrid)
177 function enableTypeControls() {
178 $this->type_controls = true;
182 * disables the type controls (map/satellite/hybrid)
185 function disableTypeControls() {
186 $this->type_controls = false;
190 * set default map type (map/satellite/hybrid)
193 function setMapType($type) {
194 switch($type) {
195 case 'hybrid':
196 $this->map_type = 'G_HYBRID_MAP';
197 break;
198 case 'satellite':
199 $this->map_type = 'G_SATELLITE_MAP';
200 break;
201 case 'map':
202 default:
203 $this->map_type = 'G_NORMAL_MAP';
204 break;
209 * enables onload
212 function enableOnLoad() {
213 $this->onload = true;
217 * disables onload
220 function disableOnLoad() {
221 $this->onload = false;
225 * enables sidebar
228 function enableSidebar() {
229 $this->sidebar = true;
233 * disables sidebar
236 function disableSidebar() {
237 $this->sidebar = false;
241 * enables map directions inside info window
244 function enableDirections() {
245 $this->directions = true;
249 * disables map directions inside info window
252 function disableDirections() {
253 $this->directions = false;
257 * enable map marker info windows
259 function enableInfoWindow() {
260 $this->info_window = true;
264 * disable map marker info windows
266 function disableInfoWindow() {
267 $this->info_window = false;
271 * set the info window trigger action
273 * @params $message string click/mouseover
275 function setInfoWindowTrigger($type) {
276 switch($type) {
277 case 'mouseover':
278 $this->window_trigger = 'mouseover';
279 break;
280 default:
281 $this->window_trigger = 'click';
282 break;
287 * enable zoom to encompass makers
289 function enableZoomEncompass() {
290 $this->zoom_encompass = true;
294 * disable zoom to encompass makers
296 function disableZoomEncompass() {
297 $this->zoom_encompass = false;
301 * set the boundary fudge factor
303 function setBoundsFudge($val) {
304 $this->bounds_fudge = $val;
308 * enables the scale map control
311 function enableScaleControl() {
312 $this->scale_control = true;
316 * disables the scale map control
319 function disableScaleControl() {
320 $this->scale_control = false;
324 * enables the overview map control
327 function enableOverviewControl() {
328 $this->overview_control = true;
332 * disables the overview map control
335 function disableOverviewControl() {
336 $this->overview_control = false;
341 * set the lookup service to use for geocode lookups
342 * default is YAHOO, you can also use GOOGLE.
343 * NOTE: GOOGLE can to intl lookups, but is not an
344 * official API, so use at your own risk.
347 function setLookupService($service) {
348 switch($service) {
349 case 'GOOGLE':
350 $this->lookup_service = 'GOOGLE';
351 break;
352 case 'YAHOO':
353 default:
354 $this->lookup_service = 'YAHOO';
355 break;
361 * adds a map marker by address
363 * @param string $address the map address to mark (street/city/state/zip)
364 * @param string $title the title display in the sidebar
365 * @param string $html the HTML block to display in the info bubble (if empty, title is used)
367 function addMarkerByAddress($address,$title = '',$html = '',$tooltip = '',$id = '') {
368 if(($_geocode = $this->getGeocode($address)) === false)
369 return false;
370 return $this->addMarkerByCoords($_geocode['lon'],$_geocode['lat'],$title,$html,$tooltip);
374 * adds a map marker by geocode
376 * @param string $lon the map longitude (horizontal)
377 * @param string $lat the map latitude (vertical)
378 * @param string $title the title display in the sidebar
379 * @param string $html|array $html
380 * string: the HTML block to display in the info bubble (if empty, title is used)
381 * array: The title => content pairs for a tabbed info bubble
383 // TODO make it so you can specify which tab you want the directions to appear in (add another arg)
384 function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '',$id = '', $html_pedidos = '') {
385 $_marker['lon'] = $lon;
386 $_marker['lat'] = $lat;
387 $_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
388 $_marker['title'] = $title;
389 $_marker['tooltip'] = $tooltip;
390 $_marker['id'] = $id;
391 $_marker['html_pedidos'] = $html_pedidos;
393 $this->_markers[] = $_marker;
394 $this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
395 // return index of marker
396 // HACK
397 return count($this->_markers) - 1;
398 // HACK
401 // HACK
402 function deleteMarkers() {
403 unset ($this->_markers);
404 return;
407 * adds a map polyline by address
408 * if color, weight and opacity are not defined, use the google maps defaults
410 * @param string $address1 the map address to draw from
411 * @param string $address2 the map address to draw to
412 * @param string $color the color of the line (format: #000000)
413 * @param string $weight the weight of the line in pixels
414 * @param string $opacity the line opacity (percentage)
416 function addPolyLineByAddress($address1,$address2,$color='',$weight=0,$opacity=0) {
417 if(($_geocode1 = $this->getGeocode($address1)) === false)
418 return false;
419 if(($_geocode2 = $this->getGeocode($address2)) === false)
420 return false;
421 return $this->addPolyLineByCoords($_geocode1['lon'],$_geocode1['lat'],$_geocode2['lon'],$_geocode2['lat'],$color,$weight,$opacity);
425 * adds a map polyline by map coordinates
426 * if color, weight and opacity are not defined, use the google maps defaults
428 * @param string $lon1 the map longitude to draw from
429 * @param string $lat1 the map latitude to draw from
430 * @param string $lon2 the map longitude to draw to
431 * @param string $lat2 the map latitude to draw to
432 * @param string $color the color of the line (format: #000000)
433 * @param string $weight the weight of the line in pixels
434 * @param string $opacity the line opacity (percentage)
436 function addPolyLineByCoords($lon1,$lat1,$lon2,$lat2,$color='',$weight=0,$opacity=0) {
437 $_polyline['lon1'] = $lon1;
438 $_polyline['lat1'] = $lat1;
439 $_polyline['lon2'] = $lon2;
440 $_polyline['lat2'] = $lat2;
441 $_polyline['color'] = $color;
442 $_polyline['weight'] = $weight;
443 $_polyline['opacity'] = $opacity;
444 $this->_polylines[] = $_polyline;
445 $this->adjustCenterCoords($_polyline['lon1'],$_polyline['lat1']);
446 $this->adjustCenterCoords($_polyline['lon2'],$_polyline['lat2']);
447 // return index of polyline
448 return count($this->_polylines) - 1;
452 * adjust map center coordinates by the given lat/lon point
454 * @param string $lon the map latitude (horizontal)
455 * @param string $lat the map latitude (vertical)
457 function adjustCenterCoords($lon,$lat) {
458 if(strlen((string)$lon) == 0 || strlen((string)$lat) == 0)
459 return false;
460 $this->_max_lon = (float) max($lon, $this->_max_lon);
461 $this->_min_lon = (float) min($lon, $this->_min_lon);
462 $this->_max_lat = (float) max($lat, $this->_max_lat);
463 $this->_min_lat = (float) min($lat, $this->_min_lat);
465 $this->center_lon = (float) ($this->_min_lon + $this->_max_lon) / 2;
466 $this->center_lat = (float) ($this->_min_lat + $this->_max_lat) / 2;
467 return true;
471 * set map center coordinates to lat/lon point
473 * @param string $lon the map latitude (horizontal)
474 * @param string $lat the map latitude (vertical)
476 function setCenterCoords($lon,$lat) {
477 $this->center_lat = (float) $lat;
478 $this->center_lon = (float) $lon;
482 * generate an array of params for a new marker icon image
483 * iconShadowImage is optional
484 * If anchor coords are not supplied, we use the center point of the image by default.
485 * Can be called statically. For private use by addMarkerIcon() and setMarkerIcon()
487 * @param string $iconImage URL to icon image
488 * @param string $iconShadowImage URL to shadow image
489 * @param string $iconAnchorX X coordinate for icon anchor point
490 * @param string $iconAnchorY Y coordinate for icon anchor point
491 * @param string $infoWindowAnchorX X coordinate for info window anchor point
492 * @param string $infoWindowAnchorY Y coordinate for info window anchor point
494 function createMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
495 $_icon_image_path = $iconImage;
497 if(!($_image_info = @getimagesize($_icon_image_path))) {
498 die('GoogleMapAPI:createMarkerIcon: Error reading image [1]: ' . $iconImage);
501 if($iconShadowImage) {
502 $_shadow_image_path = $iconShadowImage;
503 if(!($_shadow_info = @getimagesize($_shadow_image_path))) {
504 die('GoogleMapAPI:createMarkerIcon: Error reading image [2]: ' . $iconShadowImage);
509 if($iconAnchorX === 'x') {
510 $iconAnchorX = (int) ($_image_info[0] / 2);
512 if($iconAnchorY === 'x') {
513 $iconAnchorY = (int) ($_image_info[1] / 2);
515 if($infoWindowAnchorX === 'x') {
516 $infoWindowAnchorX = (int) ($_image_info[0] / 2);
518 if($infoWindowAnchorY === 'x') {
519 $infoWindowAnchorY = (int) ($_image_info[1] / 2);
523 $icon_info = array(
524 'image' => $iconImage,
525 'iconWidth' => $_image_info[0],
526 'iconHeight' => $_image_info[1],
527 'iconAnchorX' => $iconAnchorX,
528 'iconAnchorY' => $iconAnchorY,
529 'infoWindowAnchorX' => $infoWindowAnchorX,
530 'infoWindowAnchorY' => $infoWindowAnchorY
534 if($iconShadowImage) {
535 $icon_info = array_merge($icon_info, array('shadow' => $iconShadowImage,
536 'shadowWidth' => '100', $_shadow_info[0],
537 'shadowHeight' => '100', $_shadow_info[1]));
541 return $icon_info;
545 * set the marker icon for ALL markers on the map
547 function setMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
548 $this->_icons = array($this->createMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY));
552 * add an icon to go with the correspondingly added marker
554 function addMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') {
555 $this->_icons[] = $this->createMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY);
556 return count($this->_icons) - 1;
561 * print map javascript (put just before </body>, or in <header> if using onLoad())
564 function printMapJS() {
565 echo $this->getMapJS();
569 * return map javascript
572 function getMapJS() {
573 $_output = '<script type="text/javascript" charset="utf-8">' . "\n";
574 $_output .= '//<![CDATA[' . "\n";
575 $_output .= "/*************************************************\n";
576 $_output .= " * Created with GoogleMapAPI " . $this->_version . "\n";
577 $_output .= " * Author: Monte Ohrt <monte AT ohrt DOT com>\n";
578 $_output .= " * Copyright 2005-2006 New Digital Group\n";
579 $_output .= " * http://www.phpinsider.com/php/code/GoogleMapAPI/\n";
580 $_output .= " *************************************************/\n";
582 $_output .= 'function fix6ToString(n) { return n.toFixed(6).toString();} ';
583 $_output .= 'var points = [];' . "\n";
584 $_output .= 'var markers = [];' . "\n";
585 $_output .= 'var counter = 0;' . "\n";
586 if($this->sidebar) {
587 $_output .= 'var sidebar_html = "";' . "\n";
588 $_output .= 'var marker_html = [];' . "\n";
591 if(!empty($this->_icons)) {
592 $_output .= 'var icon = [];' . "\n";
593 for($i = 0, $j = count($this->_icons); $i<$j; $i++) {
594 $info = $this->_icons[$i];
596 // hash the icon data to see if we've already got this one; if so, save some javascript
597 $icon_key = md5(serialize($info));
598 if(!isset($exist_icn[$icon_key])) {
600 $_output .= "icon[$i] = new GIcon();\n";
601 $_output .= sprintf('icon[%s].image = "%s";',$i,$info['image']) . "\n";
602 if(isset($info['shadow'])) {
603 $_output .= sprintf('icon[%s].shadow = "%s";',$i,$info['shadow']) . "\n";
604 $_output .= sprintf('icon[%s].shadowSize = new GSize(%s,%s);',$i,$info['shadowWidth'],$info['shadowHeight']) . "\n";
606 $_output .= sprintf('icon[%s].iconSize = new GSize(%s,%s);',$i,$info['iconWidth'],$info['iconHeight']) . "\n";
607 $_output .= sprintf('icon[%s].iconAnchor = new GPoint(%s,%s);',$i,$info['iconAnchorX'],$info['iconAnchorY']) . "\n";
608 $_output .= sprintf('icon[%s].infoWindowAnchor = new GPoint(%s,%s);',$i,$info['infoWindowAnchorX'],$info['infoWindowAnchorY']) . "\n";
609 } else {
610 $_output .= "icon[$i] = icon[$exist_icn[$icon_key]];\n";
615 $_output .= 'var map = null;' . "\n";
617 if($this->onload) {
618 $_output .= 'function onLoad() {' . "\n";
621 $_output .= sprintf('var mapObj = document.getElementById("%s");',$this->map_id) . "\n";
622 $_output .= 'if (mapObj != "undefined" && mapObj != null) {' . "\n";
623 $_output .= sprintf('map = new GMap2(document.getElementById("%s"));',$this->map_id) . "\n";
624 if(isset($this->center_lat) && isset($this->center_lon)) {
625 // Special care for decimal point in lon and lat, would get lost if "wrong" locale is set; applies to (s)printf only
626 $_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";
629 // zoom so that all markers are in the viewport
630 if($this->zoom_encompass && count($this->_markers) > 1) {
631 // increase bounds by fudge factor to keep
632 // markers away from the edges
633 $_len_lon = $this->_max_lon - $this->_min_lon;
634 $_len_lat = $this->_max_lat - $this->_min_lat;
635 $this->_min_lon -= $_len_lon * $this->bounds_fudge;
636 $this->_max_lon += $_len_lon * $this->bounds_fudge;
637 $this->_min_lat -= $_len_lat * $this->bounds_fudge;
638 $this->_max_lat += $_len_lat * $this->bounds_fudge;
640 $_output .= "var bds = new GLatLngBounds(new GLatLng($this->_min_lat, $this->_min_lon), new GLatLng($this->_max_lat, $this->_max_lon));\n";
641 $_output .= 'map.setZoom(map.getBoundsZoomLevel(bds));' . "\n";
644 if($this->map_controls) {
645 if($this->control_size == 'large')
646 $_output .= 'map.addControl(new GLargeMapControl());' . "\n";
647 else
648 $_output .= 'map.addControl(new GSmallMapControl());' . "\n";
649 } else {
650 $_output .= 'map.disableDoubleClickZoom()' . "\n";
653 if($this->type_controls) {
654 $_output .= 'map.addControl(new GMapTypeControl());' . "\n";
657 if($this->scale_control) {
658 $_output .= 'map.addControl(new GScaleControl());' . "\n";
661 if($this->overview_control) {
662 $_output .= 'map.addControl(new GOverviewMapControl());' . "\n";
665 // HACK -> DRAG
666 if($this->disable_map_drag) {
667 $_output .= 'map.disableDragging();'."\n";
670 // HACK -> New Mupi
671 if($this->map_controls) {
672 $_output .= 'function mapSingleRightClick(point, src, overlay)
674 var point = map.fromContainerPixelToLatLng(point);
675 menu(\'<a onclick="menu()">Cerrar este menú</a><hr /><b>Latidud: </b>\'+fix6ToString( point.lat() )+\'<br /> <b>Longitud: </b>\'+fix6ToString( point.lng() )+\'<hr /><a target="_blank" href="./?accion=gestionar+mupis&crear=1&lat=\'+fix6ToString( point.lat() )+\'&lng=\'+fix6ToString( point.lng() )+\'&calle=\'+$("#combo_calles").val()+\'">Crear Mupi</a><br /><a target="_blank" href="./?accion=gestionar+referencias&crear=1&lat=\'+fix6ToString( point.lat() )+\'&lng=\'+fix6ToString( point.lng() )+\'&calle=\'+$("#combo_calles").val()+\'">Crear Referencia</a>\');
678 $_output .= 'GEvent.addListener(map, "singlerightclick", mapSingleRightClick);' . "\n";
681 $_output .= $this->getAddMarkersJS();
683 $_output .= $this->getPolylineJS();
685 if($this->sidebar) {
686 // HACK HACK
687 //$_output .= sprintf('document.getElementById("%s").innerHTML = "<ul class=\"gmapSidebar\">"+ sidebar_html +"<\/ul>";', $this->sidebar_id) . "\n";
688 $_output .= sprintf('document.getElementById("%s").innerHTML = "<b>Ver Eco Mupis:</b><br /><select id=\"combobox_mupis\" class=\"gmapSidebar\">"+ sidebar_html +"</select>";', 'lista_mupis') . "\n";
689 $_output .= 'click_sidebar($("#combobox_mupis").val())'."\n";
690 $_output .= '$("#combobox_mupis").change(function (){click_sidebar($("#combobox_mupis").val());})'."\n";
693 $_output .= '}' . "\n";
695 if($this->onload) {
696 $_output .= '}' . "\n";
699 $_output .= $this->getCreateMarkerJS();
701 // Utility functions used to distinguish between tabbed and non-tabbed info windows
702 $_output .= 'function isArray(a) {return isObject(a) && a.constructor == Array;}' . "\n";
703 $_output .= 'function isObject(a) {return (a && typeof a == \'object\') || isFunction(a);}' . "\n";
704 $_output .= 'function isFunction(a) {return typeof a == \'function\';}' . "\n";
706 if($this->sidebar) {
707 $_output .= 'function click_sidebar(idx) {' . "\n";
708 //$_output .= ' alert(idx);' . "\n";
709 $_output .= ' if(isArray(marker_html[idx])) { markers[idx].openInfoWindowTabsHtml(marker_html[idx]); }' . "\n";
710 $_output .= ' else { markers[idx].openInfoWindowHtml(marker_html[idx]); }' . "\n";
711 $_output .= ' GEvent.trigger(markers[idx],"'.$this->window_trigger.'");' . "\n";
712 $_output .= '}' . "\n";
715 $_output .= 'function showInfoWindow(idx,html) {' . "\n";
716 $_output .= 'map.centerAtLatLng(points[idx]);' . "\n";
717 $_output .= 'markers[idx].openInfoWindowHtml(html);' . "\n";
718 $_output .= '}' . "\n";
720 $_output .= '//]]>' . "\n";
721 $_output .= '</script>' . "\n";
722 return $_output;
726 * overridable function for generating js to add markers
728 function getAddMarkersJS() {
729 $SINGLE_TAB_WIDTH = 88; // constant: width in pixels of each tab heading (set by google)
730 $i = 0;
731 $_output = '';
732 foreach($this->_markers as $_marker) {
733 if(is_array($_marker['html'])) {
734 // warning: you can't have two tabs with the same header. but why would you want to?
735 $ti = 0;
736 $num_tabs = count($_marker['html']);
737 $tab_obs = array();
738 foreach($_marker['html'] as $tab => $info) {
739 if($ti == 0 && $num_tabs > 2) {
740 $width_style = sprintf(' style=\"width: %spx\"', $num_tabs * $SINGLE_TAB_WIDTH);
741 } else {
742 $width_style = '';
744 $tab = str_replace('"','\"',$tab);
745 $info = str_replace('"','\"',$info);
746 $info = str_replace(array("\n", "\r"), "", $info);
747 $tab_obs[] = sprintf('new GInfoWindowTab("%s", "%s")', $tab, '<div id=\"gmapmarker\"'.$width_style.'>' . $info . '</div>');
748 $ti++;
750 $iw_html = '[' . join(',',$tab_obs) . ']';
751 } else {
752 $iw_html = "<div id='gmapmarker'>" . str_replace(array("\n", "\r"), "", $_marker['html']) . "</div>";
754 // HACK ID
755 $_output .= sprintf('var point = new GLatLng(%s,%s);',$_marker['lat'],$_marker['lon']) . "\n";
756 $_output .= sprintf('var marker = createMarker(point,"%s","%s", %s,"%s","%s","%s");',
757 str_replace('"','\"',$_marker['title']),
758 $iw_html,
760 str_replace('"','\"',$_marker['tooltip']),
761 $_marker['id'],
762 $_marker['html_pedidos']) . "\n";
763 //TODO: in above createMarker call, pass the index of the tab in which to put directions, if applicable
764 $_output .= 'map.addOverlay(marker);' . "\n";
765 $i++;
767 return $_output;
771 * overridable function to generate polyline js
773 function getPolylineJS() {
774 $_output = '';
775 foreach($this->_polylines as $_polyline) {
776 $_output .= sprintf('var polyline = new GPolyline([new GLatLng(%s,%s),new GLatLng(%s,%s)],"%s",%s,%s);',
777 $_polyline['lat1'],$_polyline['lon1'],$_polyline['lat2'],$_polyline['lon2'],$_polyline['color'],$_polyline['weight'],$_polyline['opacity'] / 100.0) . "\n";
778 $_output .= 'map.addOverlay(polyline);' . "\n";
780 return $_output;
784 * overridable function to generate the js for the js function for creating a marker.
786 // IMPORTANTE!, acá tiene que ir el hack mayor!.
787 function getCreateMarkerJS() {
788 $_SCRIPT_ = '$.get(\'contenido/mupis+ubicaciones+dinamico.php?accion=mupi&MUPI=\'+id, function(data){
789 $(\'div.close\').trigger("click.jGrowl");
790 $.jGrowl(data,{theme: \'globoclientes\',sticky: true,closer: false});
791 });';
792 $_output = '';
793 $_output .= 'function createMarker(point, title, html, n, tooltip, id, html_pedidos) {' . "\n";
794 $_output .= 'if(n >= '. sizeof($this->_icons) .') { n = '. (sizeof($this->_icons) - 1) ."; }\n";
795 if(!empty($this->_icons)) {
796 $tmpBool = $this->disable_drag ? 'false' : 'true';
797 $_output .= 'var marker = new GMarker(point,{\'icon\': icon[n], \'title\': tooltip, \'draggable\': '.$tmpBool.', \'bouncy\': false});' . "\n";
798 } else {
799 $_output .= 'var marker = new GMarker(point,{\'title\': tooltip});' . "\n";
802 // Admin -> Open Info Window + click + Mover + Marcardores
803 // Usuario -> Click
804 if($this->info_window) {
805 $_output .= 'if (id.indexOf(\'REF\') == -1) {' . "\n";
806 if ($this->Mostrar_Contenido_Maximizado) {
807 $Contenido_maximizado = "'maxTitle': 'Edición de pedidos', 'maxContent': html_pedidos";
808 } else {
809 $Contenido_maximizado = "";
811 $_output .= 'GEvent.addListener(marker, "'.$this->window_trigger.'", function() { marker.openInfoWindowHtml(html,{'.$Contenido_maximizado.'}) });' . "\n";
812 $_output .= 'GEvent.addListener(marker, "infowindowclose", function() { $(\'div.close\').trigger("click.jGrowl");$("#botones_arte").html(""); });' . "\n";
813 $_output .= '} else {' . "\n";
814 $_output .= 'GEvent.addListener(marker, "'.$this->window_trigger.'", function() { '.$_SCRIPT_.'; });' . "\n";
815 $_output .= '}' . "\n";
816 } else {
817 $_output .= 'if (id.indexOf(\'REF\') == -1) {' . "\n";
818 $_output .= 'GEvent.addListener(marker, "'.$this->window_trigger.'", function() { '.$_SCRIPT_.'; });' . "\n";
819 $_output .= '}' . "\n";
821 if (!$this->disable_drag) {
822 $_output .= 'GEvent.addListener(marker, "dragstart", function() { map.closeInfoWindow();});' . "\n";
823 //$_output .= 'GEvent.addListener(marker, "dragend", function() { var point = marker.getPoint(); alert( id + \' \' + fix6ToString( point.lat() ) + \',\' + fix6ToString( point.lng() ) ); $("#datos_mupis").load(\'contenido/mupis+ubicaciones+dinamico.php?accion=drag&id=\'+id+\'&lat=\'+fix6ToString( point.lat() )+\'&lng=\'+fix6ToString( point.lng() )); });' . "\n";
824 $_output .= 'GEvent.addListener(marker, "dragend", function() { var point = marker.getPoint(); $("#datos_mupis").load(\'contenido/mupis+ubicaciones+dinamico.php?accion=drag&id=\'+id+\'&lat=\'+fix6ToString( point.lat() )+\'&lng=\'+fix6ToString( point.lng() )); });' . "\n";
826 $_output .= 'points[counter] = point;' . "\n";
827 $_output .= 'markers[counter] = marker;' . "\n";
828 if($this->sidebar) {
829 $_output .= 'if (id.indexOf(\'REF\') == -1) {' . "\n";
830 $_output .= 'marker_html[counter] = html;' . "\n";
831 $_output .= 'sidebar_html += \'<option class="gmapSidebarItem" id="gmapSidebarItem" value="\'+counter+\'">\' + title + \'</option>\';' . "\n";
832 $_output .= '}' . "\n";
834 $_output .= 'counter++;' . "\n";
835 $_output .= 'return marker;' . "\n";
836 $_output .= '}' . "\n";
837 return $_output;
841 * print map (put at location map will appear)
844 function printMap() {
845 echo $this->getMap();
849 * return map
852 function getMap() {
853 $_output = '';
854 if(strlen($this->width) > 0 && strlen($this->height) > 0) {
855 $_output .= sprintf('<div id="%s" style="width: %s; height: %s"></div>',$this->map_id,$this->width,$this->height) . "\n";
856 } else {
857 $_output .= sprintf('<div id="%s"></div>;',$this->map_id) . "\n";
859 return $_output;
864 * print sidebar (put at location sidebar will appear)
867 function printSidebar() {
868 echo $this->getSidebar();
872 * return sidebar html
875 function getSidebar() {
876 return sprintf('<div id="%s"></div>',$this->sidebar_id) . "\n";
880 * get the geocode lat/lon points from given address
881 * look in cache first, otherwise get from Yahoo
883 * @param string $address
885 function getGeocode($address) {
886 if(empty($address))
887 return false;
889 $_geocode = false;
891 if(($_geocode = $this->getCache($address)) === false) {
892 if(($_geocode = $this->geoGetCoords($address)) !== false) {
893 $this->putCache($address, $_geocode['lon'], $_geocode['lat']);
897 return $_geocode;
901 * get the geocode lat/lon points from cache for given address
903 * @param string $address
905 function getCache($address) {
906 if(!isset($this->dsn))
907 return false;
909 $_ret = array();
911 // PEAR DB
912 require_once('DB.php');
913 $_db =& DB::connect($this->dsn);
914 if (PEAR::isError($_db)) {
915 die($_db->getMessage());
917 $_res =& $_db->query("SELECT lon,lat FROM {$this->_db_cache_table} where address = ?", $address);
918 if (PEAR::isError($_res)) {
919 die($_res->getMessage());
921 if($_row = $_res->fetchRow()) {
922 $_ret['lon'] = $_row[0];
923 $_ret['lat'] = $_row[1];
926 $_db->disconnect();
928 return !empty($_ret) ? $_ret : false;
932 * put the geocode lat/lon points into cache for given address
934 * @param string $address
935 * @param string $lon the map latitude (horizontal)
936 * @param string $lat the map latitude (vertical)
938 function putCache($address, $lon, $lat) {
939 if(!isset($this->dsn) || (strlen($address) == 0 || strlen($lon) == 0 || strlen($lat) == 0))
940 return false;
941 // PEAR DB
942 require_once('DB.php');
943 $_db =& DB::connect($this->dsn);
944 if (PEAR::isError($_db)) {
945 die($_db->getMessage());
948 $_res =& $_db->query('insert into '.$this->_db_cache_table.' values (?, ?, ?)', array($address, $lon, $lat));
949 if (PEAR::isError($_res)) {
950 die($_res->getMessage());
952 $_db->disconnect();
954 return true;
959 * get geocode lat/lon points for given address from Yahoo
961 * @param string $address
963 function geoGetCoords($address,$depth=0) {
965 switch($this->lookup_service) {
967 case 'GOOGLE':
969 $_url = sprintf('http://%s/maps/geo?&q=%s&output=csv&key=%s',$this->lookup_server['GOOGLE'],rawurlencode($address),$this->api_key);
971 $_result = false;
973 if($_result = $this->fetchURL($_url)) {
975 $_result_parts = explode(',',$_result);
976 if($_result_parts[0] != 200)
977 return false;
978 $_coords['lat'] = $_result_parts[2];
979 $_coords['lon'] = $_result_parts[3];
982 break;
984 case 'YAHOO':
985 default:
987 $_url = 'http://%s/MapsService/V1/geocode';
988 $_url .= sprintf('?appid=%s&location=%s',$this->lookup_server['YAHOO'],$this->app_id,rawurlencode($address));
990 $_result = false;
992 if($_result = $this->fetchURL($_url)) {
994 preg_match('!<Latitude>(.*)</Latitude><Longitude>(.*)</Longitude>!U', $_result, $_match);
996 $_coords['lon'] = $_match[2];
997 $_coords['lat'] = $_match[1];
1001 break;
1004 return $_coords;
1010 * fetch a URL. Override this method to change the way URLs are fetched.
1012 * @param string $url
1014 function fetchURL($url) {
1016 return file_get_contents($url);
1021 * get distance between to geocoords using great circle distance formula
1023 * @param float $lat1
1024 * @param float $lat2
1025 * @param float $lon1
1026 * @param float $lon2
1027 * @param float $unit M=miles, K=kilometers, N=nautical miles, I=inches, F=feet
1029 function geoGetDistance($lat1,$lon1,$lat2,$lon2,$unit='K') {
1031 // calculate miles
1032 $M = 69.09 * rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2))));
1034 switch(strtoupper($unit))
1036 case 'K':
1037 // kilometers
1038 return $M * 1.609344;
1039 break;
1040 case 'N':
1041 // nautical miles
1042 return $M * 0.868976242;
1043 break;
1044 case 'F':
1045 // feet
1046 return $M * 5280;
1047 break;
1048 case 'I':
1049 // inches
1050 return $M * 63360;
1051 break;
1052 case 'M':
1053 default:
1054 // miles
1055 return $M;
1056 break;