PHP - Clase para trabajar con google maps
https://www.interviewzen.com/interview/56wsYp3 Permite interactuar desde php con la api de googlemaps. Recupera coordenadas desde una dirección. Dibuja marcadores (chinchetas), les añade comentarios y contenido.
¿Cómo se utiliza?
Ejemplo: Obtener latitud y longitud desde una dirección
<html>
<head>
<title>Goglemaps API 3 Clase PHP</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<script type="text/javascript" src="html_js/js_google/js_google_maps_3.js"></script>
</head>
<body>
<?php
include_once("google_maps_3.php");
//Obtener latitud y longitud con los datos de una dirección.
//El array debe llevar
$arDireccion[] = array
(
//"pais" => "España", //opcional
"direccion" => "La granja 8",
"zona" => "alcobendas",
"cp" => ""
);
$arDireccion[] = array
(
"pais" => "España", //opcional
"direccion" => "Conde de Peñalver 51",
"zona" => "madrid",
"cp" => "28006"
);
//creamos el objeto
$oGoogleMap = new GoogleMaps3();
//lo configuramos para que no esté acotado. Es decir que si encuentra la
//dirección 0 fuera de España. p.e Latinoamérica, que obtenga los datos.
$oGoogleMap->dont_narrow();
//La función bug es un var_dump() customizado. Sirve para mostrar trazas.
bug($oGoogleMap->get_latlong_from_address($arDireccion[0]),$arDireccion[0]["direccion"]);
bug($oGoogleMap->get_latlong_from_address($arDireccion[1]),$arDireccion[1]["direccion"]);
//Esta traza mostraria lo siguiente:
//VARIABLE La granja 8:
//array(2){["latitude"]=>float(40.5475437)["longitude"]=>float(-3.6420912)}
//VARIABLE Conde de Peñalver 51:
//array(2){["latitude"]=>float(40.4363505) ["longitude"]=>float(-3.685144)}
?>
<div id="map_canvas"></div>
</body>
</html>
Ejemplo: Posicionar marcadores (chinchetas, globos) en googlemap
<html>
<head>
<title>Goglemaps API 3 Clase PHP</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<script type="text/javascript" src="html_js/js_google/js_google_maps_3.js"></script>
</head>
<body>
<?php
include_once("google_maps_3.php");
//Los marcadores identifican a los globitos o chinchetas en el mapa.
//El formato de los indices del array a pasar en el constructor debe ser el siguiente:
//title : es equivalente al "tooltiptext" que aparece cuando se pasa el puntero
//por encima.
//content: el valor que se mostrará en el popup informativo. Se puede incluir html,
//controles y eventos.
//latitude, longitude: coordenadas de tipo real
//PENDIENTE: Un indice "address" para poder crear un marcador directamente desde
//este dato. De momento no lo hace.
//El orden de los arrays anidados influira en el número que se asigna al marcador.
$arMarcadores[]=array(
"title"=>"uno ","content"=>"<b>Content 1</b><input type=\"text\" value=\"marcador uno\">",
"latitude"=>"40.5475437","longitude"=>"-3.6420912"
);
$arMarcadores[]=array(
"title"=>"dos ","content"=>"<b>Content 2</b>",
"latitude"=>"40.4363505","longitude"=>"-3.685144"
);
$arMarcadores[]=array(
"title"=>"tres ","content"=>"<b>Content 3</b>",
"latitude"=>"41.4166909","longitude"=>"-3.7003454"
);
$oGoogleMap = new GoogleMaps3($arMarcadores);
//Configuramos el zoom
$oGoogleMap->set_zoom(7);
//Dibujamos las lineas entre los marcadores (pines)
$oGoogleMap->draw_lines();
//Tamaño del mapa
$oGoogleMap->set_size_container(800,600);
//Unidad del tamaño del mapa. Solo acepta pt y px. He probado con % y no va.
$oGoogleMap->set_size_unit('pt');
//No se mostrarán numeros en los pines de googlemaps
$oGoogleMap->set_markers_numbers_off();
//Calcula la distancia entre las chinchetas
$fDistancia = $oGoogleMap->sum_distance();
//bug($fDistancia); muestra 11.1
//Ejecuta la creación del mapa en el div "map_canvas"
$oGoogleMap->draw_map();
?>
<div id="map_canvas"></div>
</body>
</html>
¿Qúé se necesita?
En principio solo dos archivos:- js_google_maps_3.js
- google_maps_3.php
La clase javascript que actua directamente sobre el api de googlemaps
La clase que hace de puente entre nuestro objeto php y el objeto javascript
Clase php GoogleMaps3
/**
* @author Eduardo Acevedo Farje.
* @link www.eduardoaf.com
* @version 1.0.7
* @name Component GoogleMaps3
* @uses js_google_map_3.js, jquery v1.7+
*/
class GoogleMaps3
{
private $_sApikey = "";
//Indica si se cargara automaticamente el tag "<script>" con la url
//de googlemaps. Si se ha definido una apikey se incluye
private $_isAutoApikey = true;
//Indica si se va a incluir la libreria jquery desde google.
//Si dispones de una copia local se puede desactivar.
private $_useGoogleJquery = true;
//FOR JS
//Estos son parametros de configuración para el archivo: js_google_map_3.js
private $_arMarkers = "[]"; //Las chinchetas
private $_useMakersNumbers = true; //Si las chinchetas mostrarán números.
private $_sMapType = "'roadmap'"; //El tipo de mapa.
//Elemento div donde se mostrará el mapa generado.
private $_sIdDivContainer = "'map_canvas'";
//El zoom
private $_iZoom = 6;
//Punto inicial de muestreo. Cuando se crea el mapa debe mostrar algún punto
//he escogido las coord. de la Puerta del Sol (Madrid)
private $_fLatitude = 40.41694;
private $_fLongitude = -3.70361;
//Indica si ha de pintarse lineas entre las chinchetas (Markers).
private $_drawLines = false;
//Configuración del tamaño del mapa y su unidad.
private $_iWidth = 800;
private $_iHeight = 600;
private $_sUnitWH = "px";
//FOR PHP
//Parametros para hacer peticiones de latitud y longitud de una dirección
//Url para enviar peticiones por get. Devolvera un objeto xml
private $_sUrlAskAddress = "http://maps.googleapis.com/maps/api/geocode/xml";
//Indica si se ha de acotar la busqueda de una dirección.
//Evita que te encuentre una dirección equivalente en otro país.
private $_doNarrowSearch = true;
//Coordenadas de acotación de España. Peninsula y Canarias.
private $_arNarrowLat = array("min"=>24.654534254781115,"max"=>45.18786629495072);
private $_arNarrowLong = array("min"=>-19.80908203125, "max"=>4.3828125);
//TODO: Direcciones a geolocalizar. Lo dejaré para otra versión.
private $_arAddresses = array();
//Indica si se ha de esperar x microsegundos a que responda la url de petición
private $_useDelay = true;
private $_iDelayTime = 250;
//Indicadores del estado de la petición de geolocalización.
private $_is_error = false;
private $_message = "";
/**
* Formato del array de marcadores:
$arMarkers[]=array
(
"title"=>"un titulo ", Lo que se mostrara al pasar el raton
"content"=>"<b>Un contenido</b>", El texto dentro del popup de dialogo
"latitude"=>"36.643271085342",
"longitude"=>"-4.578660819468"
);
* @param array $arMarkers Array anidado tipo tabla filas x columnas
* @param array $arAddresses TODO próxima entrega ;0)
*/
public function __construct($arMarkers=array(),$arAddresses=array(),$sApikey="")
{
$this->_arMarkers = $arMarkers;
$this->_arAddresses = $arAddresses;
if(!empty($sApikey)) $this->_sApikey = $sApikey;
}
//Pasa al objeto javascript los datos configurados en esta clase y despues
//ejecuta load_map(), función javascript que dibuja el mapa con los datos
//de configuración.
public function draw_map()
{
if($this->_useGoogleJquery) $this->show_google_jquery_tag();
if($this->_isAutoApikey) $this->show_apikey_tag();
?>
<script type="text/javascript">
gmaps3.config.arMarkers = <?php $this->show_js_array_table(); ?>;
gmaps3.config.sIdDivContainer = <?php $this->get_div_container(); ?>;
gmaps3.config.iZoom = <?php $this->get_zoom(); ?>;
gmaps3.config.fLatitude = <?php $this->get_latitude(); ?>;
gmaps3.config.fLongitude = <?php $this->get_longitude(); ?>;
gmaps3.config.sMapType = <?php $this->get_maptype(); ?>;
gmaps3.config.useMarkersNumbers = <?php $this->is_makers_with_numbers(); ?>;
gmaps3.config.drawLines = <?php $this->do_draw_lines(); ?>;
gmaps3.config.iHeight = <?php $this->get_height(); ?>;
gmaps3.config.iWidth = <?php $this->get_width(); ?>;
gmaps3.config.sUnitWH = <?php $this->get_size_unit(); ?>;
//bug(gmaps3,"gmaps3"); //La función bug es equivalente a console.debug
//bug(gmaps3.config.arMarkers,"markers");
jQuery(document).ready(gmaps3.load_map);
</script>
<?php
}
/*
* Imprime en pantalla un array javascript de dos dimensiones.
*/
private function show_js_array_table()
{
echo $this->get_js_as_array_table();
}
/*
* Devuelve un string js con el formato de un array generado desde
* $this_arMarkers
*/
private function get_js_as_array_table()
{
$arTable = $this->_arMarkers;
$arItems = array();
$sJsArray = "[";
foreach($arTable as $i=>$arRow)
$arItems[] = $this->get_as_js_array_row($arRow);
if(!empty($arItems)) $sJsArray .= implode(",", $arItems);
$sJsArray .= "]";
return $sJsArray;
}
/**
* Se le pasa un array de tipo columnas y lo convierte en array js
* @param array $arRow tipo array("nombre_columna"=>"valor",..,)
* @return string Cadena de texto en formato array
*/
private function get_as_js_array_row($arRow=array())
{
$arItems = array();
$sJsArray = "[";
foreach($arRow as $key=>$sFieldValue)
{
switch($key)
{
case "content":
case "title":
$arItems[] = $this->get_as_js_string($sFieldValue);
break;
case "number":
case "latitude":
case "longitude":
case "zindex":
$arItems[] = $sFieldValue;
break;
}
}
if(!empty($arItems)) $sJsArray .= implode(",", $arItems);
$sJsArray .= "]\n";
return $sJsArray;
//['sTitle', fLat, fLong, iZindex, sContent, iIconNumber]
}
/**
* Se utiliza para generar un array de substrings
* @param string $sValue
* @return string algo como '1'. Asi js lo entenderá como un string.
*/
private function get_as_js_string($sValue)
{
return "'$sValue'";
}
/**
*
* @param array $arPoint1 array("latitude"=>valor,"longitude"=>valor)
* @param array $arPoint2 array("latitude"=>valor,"longitude"=>valor)
* @return float distancia redondeada a dos decimales.
*/
public function distance_calculation(array $arPoint1, array $arPoint2)
{
$fX1 = $arPoint1["latitude"];
$fY1 = $arPoint1["longitude"];
$fX2 = $arPoint2["latitude"];
$fY2 = $arPoint2["longitude"];
if(is_numeric($fX1)&&is_numeric($fY1)&&is_numeric($fX2)&&is_numeric($fY2))
$fX1 = sqrt(pow(($fX1 - $fX2),2) + pow(($fY1-$fY2),2));
$fX1 = round($fX1, 2);
return (float)$fX1;
}
/*
* Dependiendo de los datos de las chinchetas se va calculando las distancias
* ojo, NO EL RECORRIDO.
*/
public function sum_distance()
{
$arPoint1 = array("latitude"=>0,"longitude"=>0);
$arPoint2 = array("latitude"=>0,"longitude"=>0);
$iNumMarkers =count($this->_arMarkers);
$fDistance = 0;
for($i=0; $i<$iNumMarkers-1; $i++)
{
$arPoint1["latitude"] = $this->_arMarkers[$i]["latitude"];
$arPoint1["longitude"] = $this->_arMarkers[$i]["longitude"];
$arPoint2["latitude"] = $this->_arMarkers[$i+1]["latitude"];
$arPoint2["longitude"] = $this->_arMarkers[$i+1]["longitude"];
$fDistance += $this->distance_calculation($arPoint1, $arPoint2);
}
return (float)$fDistance;
}
//GETTERS
public function get_markers(){return $this->_arMarkers;}
public function is_makers_with_numbers()
{
if($this->_useMakersNumbers) echo "true";
else echo "false";
}
public function do_draw_lines()
{
if($this->_drawLines) echo "true";
else echo "false";
}
/**
* Segun un array con datos de una dirección se recupera su latitud y longitud
* @param array $arAddress array("pais"=>"España","direccion"=>"Conde de Peñalver 32", "zona"=>"Madrid", "cp"=>"28006");
*/
public function get_latlong_from_address(array $arAddress)
{
$arLl = array("latitude"=>"","longitude"=>"");
if(!empty($arAddress))
{
$sGmapAskAddress = $this->_sUrlAskAddress;
//Une con comas el array
$sAddrForUrl = join(", ",$arAddress);
//codifica el string en utf
$sAddrForUrl = utf8_encode($sAddrForUrl);
//codifica el string en formato url
$sAddrForUrl = urldecode($sAddrForUrl);
//sustituye espacios por el caracter +
$sAddrForUrl = str_replace(" ", "+", $sAddrForUrl);
$sGmapAskAddress = $sGmapAskAddress."?address=".$sAddrForUrl."&sensor=false";
//bug($sGmapAskAddress);
$oXml = simplexml_load_file($sGmapAskAddress);
//bug($oXml); die;
//Dependiendo de cuanto esté ocupado el servidor de google puede tardar mas ó menos.
//Para asegurarnos que se cree correctamente el objeto xml con los detalles de la dirección pedida
//forzamos a que el archivo espere unos instantes
if($this->_useDelay) usleep($this->_iDelayTime);//microsegundos
if($oXml!=false)
{
//bug($oXml);
$sXmlStatus = $oXml->status;
//status ok. Se ha localizado la dirección
if(strcmp($sXmlStatus,"OK") == 0)
{
$fLatitude = $oXml->result->geometry->location->lat;//v3
$fLongitude = $oXml->result->geometry->location->lng;//v3
$fLatitude = (float) $fLatitude;
$fLongitude = (float) $fLongitude;
//bug($fLatitude,"latitud"); bug($fLongitude,"longitud");
if($this->_doNarrowSearch)
{
if($this->is_in_range_latlong($fLatitude, $fLongitude))
{
$arLl["latitude"]=$fLatitude; $arLl["longitude"]=$fLongitude;
$this->_message = "Dirección encontrada";
}
//fuera de rango
else
{
//bug("fuera de rango");
$this->set_message_error("Dirección fuera de rango: Lat:$fLatitude, Long:$fLongitude");
}
}
//No se usa acotación
else
{
$arLl["latitude"]=$fLatitude; $arLl["longitude"]=$fLongitude;
$this->_message = "Dirección encontrada";
}
}
//status de xml fallido
else
{
$this->set_message_error("La dirección $sAddrForUrl no se pudo geolocalizar. Estado=$sXmlStatus");
}
}
//error en simplexml_load_file
else
{
$this->set_message_error("No se ha podido crear xml desde: $sGmapAskAddress");
}
}
return $arLl;
}
/**
* Determina si las coordenadas obtenidas de una dirección está dentro de los limites
* de acotación
* @param float $fLatitude
* @param float $fLongitude
* @return boolean
*/
private function is_in_range_latlong($fLatitude=0.0,$fLongitude=0.0)
{
//bug($this->_arNarrowLat,"lat"); bug($fLatitude,"lat"); bug($this->_arNarrowLong,"long"); bug($fLongitude,"long");
//bug($this->comapre_float($fLatitude,"<",$this->_arNarrowLat["max"]),"lat < latmax?");
//bug($this->comapre_float($this->_arNarrowLat["min"],"<",$fLatitude),"latmin > latitude?");
//bug($this->comapre_float($fLongitude,"<",$this->_arNarrowLong["max"]),"long < longmax?");
//bug($this->comapre_float($this->_arNarrowLong["min"],"<",$fLongitude),"longmin > longitude?");
$isInRange =
(
$this->comapre_float($fLatitude,"<",$this->_arNarrowLat["max"]) &&
$this->comapre_float($this->_arNarrowLat["min"],"<",$fLatitude) &&
$this->comapre_float($fLongitude,"<",$this->_arNarrowLong["max"]) &&
$this->comapre_float($this->_arNarrowLong["min"],"<",$fLongitude)
);
return $isInRange;
}
/**
* Función para comparar números en coma flotante (eaf)
* La comparación de números en coma flotante no es tribial. No se puede
* utilizar por ejemplo: $float1>$float2... es decir, los operadores comunes.
* Esta función pasa los numeros a binarios con una precision marcada
* @param float $float1
* @param char $cOperator =, <, >, <=, >= !=
* @param float $float2
* @param integer $iPrecision
* @return boolean o "operator error";
*/
private function comapre_float($float1,$cOperator="=",$float2,$iPrecision=10)
{
//Siempre la comparación se hace de float1 con respecto a float1
// si el resultado es: 0 son igulaes, -1 f1 menor, 1 f1 mayor
switch (trim($cOperator))
{
case "=":
return bccomp($float1, $float2, $iPrecision)==0;
break;
case "<":
return bccomp($float1, $float2, $iPrecision)==-1;
break;
case ">":
return bccomp($float1, $float2, $iPrecision)==1;
break;
case "!=":
return !(compare_float($float1,"=",$float2, $iPrecision));
break;
case ">=":
return compare_float($float1,">",$float2, $iPrecision)
||compare_float($float1,"=",$float2, $iPrecision);
break;
case "<=":
return compare_float($float1,"<",$float2, $iPrecision)
||compare_float($float1,"=",$float2, $iPrecision);
break;
default:
return "operator error";
break;
}
}
//Devuelve un string con el tag de javascript de la libreria jquery
public function get_google_jquery()
{
$sTagJquery = "<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>\n";
return $sTagJquery;
}
public function show_google_jquery_tag(){echo $this->get_google_jquery();}
public function get_apikey_tag()
{
$sApiUrl = "";
//bug($this->_sApikey);
if(!empty($this->_sApikey))
$sApiUrl = "<script type=\"text/javascript\" src=\"http://maps.googleapis.com/maps/api/js?key=$this->_sApikey&sensor=false\"></script>\n";
else
$sApiUrl = "<script type=\"text/javascript\" src=\"http://maps.googleapis.com/maps/api/js?sensor=false\"></script>\n";
return $sApiUrl;
}
public function show_apikey_tag(){echo $this->get_apikey_tag();}
private function get_maptype(){echo $this->_sMapType;}
private function get_div_container(){echo $this->_sIdDivContainer;}
private function get_zoom(){echo $this->_iZoom;}
private function get_latitude(){ echo $this->_fLatitude; }
private function get_longitude(){ echo $this->_fLongitude; }
private function get_height(){echo $this->_iHeight;}
private function get_width(){echo $this->_iWidth;}
private function get_size_unit(){echo "'$this->_sUnitWH'";}
private function get_message(){return $this->_message;}
public function get_sApikey(){ return $this->_sApikey;}
//SETTERS
public function set_markers($arMarkers=array()){ $this->_arMarkers = $arMarkers; }
public function set_markers_numbers_off($isOn=false){$this->_useMakersNumbers = $isOn;}
public function set_maptype($sValue){$this->_sMapType = strtolower("'$sValue'");}
public function set_div_container($sValue){ $this->_sIdDivContainer = "'$sValue'"; }
public function set_zoom($iZoom){ $this->_iZoom = $iZoom; }
public function set_latitude($fLatitude){ $this->_fLatitude = $fLatitude; }
public function set_longitude($fLongitude){ $this->_fLongitude = $fLongitude; }
public function draw_lines($isOn=true){ $this->_drawLines = $isOn; }
public function set_size_container($iWidth=800,$iHeight=600)
{
if(!empty($iHeight))$this->_iHeight = $iHeight;
if(!empty($iWidth)) $this->_iWidth = $iWidth;
}
public function set_size_unit($sType="pt"){ $this->_sUnitWH = $sType; }
public function add_address(array $arAddress){ $this->_arAddresses[] = $arAddress; }
private function set_message_error($sMessage,$isError=true)
{
$this->_is_error = $isError;
$this->_message = $sMessage;
}
/**
* Solo influye para recuperar latitud y longitud de direcciones.
* No en el pintado de marcadores
* @param boolean $isOn
*/
public function no_narrow($isOn=false){ $this->_doNarrowSearch = $isOn; }
public function set_delay_time($iMicroSeconds){$this->_iDelayTime = $iMicroSeconds;}
public function no_dalay($isOn=false){ $this->_useDelay = $isOn; }
public function set_apikey($sApikey){$this->_sApikey = $sApikey;}
public function no_auto_apikey($isOn=false){$this->_isAutoApikey = $isOn;}
public function no_google_jquery($isOn=false){$this->_useGoogleJquery = $isOn;}
}
Clase javascript gmaps3
/**
* @author Eduardo Acevedo Farje.
* @link www.eduardoaf.com
* @version 1.0.4
* @name Javascript class for GoogleMaps3
* @uses google_maps_3.php, jquery v1.7+
*/
//La función bug es equivalente a la de php. Imprime trazas en la consola
//de firebug
var bug = function(value,title)
{
if(window.console != undefined)
{
if(title!=null) console.debug(title);
console.debug(value);
}
};
var gmaps3 =
{
config :
{
sMapType : 'roadmap',
sIdDivContainer : 'map_canvas', //Div contenedor
iZoom : 6,
fLatitude : 40.41694, //Puerta del sol (Madrid).
fLongitude : -3.70361,
arMarkers : [],
useMarkersNumbers : true,
drawLines : false,
iWidth : 800,
iHeight: 600,
sUnitWH : 'px'
},
//arLocations: [sTitle, sContent, fLatitude, fLongitude],..[]
draw_markers : function(arMarkers)
{
var arTmpMarker;
var oLatLng;
var sTitle;
var sContent;
var iMarkerNumber;
var iCoordZ;
for(var i = 0; i < arMarkers.length; i++)
{
arTmpMarker = arMarkers[i];
sTitle = arTmpMarker[0];
sContent = arTmpMarker[1];
oLatLng = new google.maps.LatLng(arTmpMarker[2], arTmpMarker[3]);
iMarkerNumber = i+1;
iCoordZ = i+1;
//bug(oLatLng,"oLatLng");
//iIconNumber = arTmpLocation[5];
this.draw_marker(sTitle, sContent, oLatLng, iMarkerNumber, iCoordZ);
}
},
//https://developers.google.com/maps/documentation/javascript/overlays#Markers
draw_marker : function(sTitle, sContent, oLatLng, iNumber, iCoordZ,
oMiImage,oMiShadow,oMiIcon,oShape)
{
var sIconUrl = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=';
var sEndIconUrl = '|FE6256|000000';
var oInfoWindow = null;
var oMarker = new google.maps.Marker
(
{
map: this.oMap,
title: sTitle,
position: oLatLng,
zIndex: iCoordZ,
image: oMiImage, //oMarkerImage
shadow: oMiShadow, //oMarkerImage
icon: oMiIcon, //oMarkerImage
shape: oShape // coord: [1, 1, 1, 20, 18, 20, 18 , 1], type: 'poly'
}
);
if(oMiIcon==null && iNumber!='' && gmaps3.config.useMarkersNumbers)
oMarker.icon = sIconUrl + iCoordZ + sEndIconUrl;
if(sContent!=null && jQuery.trim(sContent)!='')
{
oInfoWindow = new google.maps.InfoWindow
(
{ content: sContent }
);
var on_click = function()
{
oInfoWindow.open(gmaps3.oMap,oMarker);
}
google.maps.event.addListener(oMarker,'click',on_click);
}
//bug(oMarker,"oMarker");
},
draw_lines : function(arLatLong)
{
var arObjectsLl = [];
var fLat = 0;
var fLong = 0;
var arTmpLatLong = [];
var oTmpLatLng = null;
for(var i = 0; i < arLatLong.length; i++)
{
arTmpLatLong = arLatLong[i];
fLat = arTmpLatLong[0];
fLong = arTmpLatLong[1];
oTmpLatLng = new google.maps.LatLng(fLat, fLong);
arObjectsLl.push(oTmpLatLng);
}
//bug(arObjectsLl,"arObjectsLi");
var oPolyLine = new google.maps.Polyline
(
{
path: arObjectsLl,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
}
);
oPolyLine.setMap(gmaps3.oMap);
},
get_maptype : function(sType)
{
var oMapTypeId = null;
var sType = sType || this.config.sMapType;
sType = sType.toLowerCase();
if(sType=="roadmap")
{
oMapTypeId = google.maps.MapTypeId.ROADMAP;
}
else if(sType=="satelite")
{
oMapTypeId = google.maps.MapTypeId.SATELITE;
}
else if(sType=="hybrid")
{
oMapTypeId = google.maps.MapTypeId.HYBRID;
}
else //if(sType="terrain")
{
oMapTypeId = google.maps.MapTypeId.TERRAIN;
}
return oMapTypeId;
},
extract_latlong_from_markers : function(arMarkers, asGoogleObj)
{
var arMarkers = arMarkers || this.config.arMarkers;
var arLatLong = [];
var arTemp = [];
var fLatitude = 0;
var fLongitude = 0;
//Los marcadores es un array de arrays cuyas filas llevan como
//campos los datos a mostrar en pantalla
for(var i=0; i<arMarkers.length i++)
{
arTemp = arMarkers[i];
fLatitude = arTemp[2];
fLongitude = arTemp[3];
if(asGoogleObj==null) arTemp = [fLatitude,fLongitude];
else arTemp = new google.maps.LatLng(fLatitude,fLongitude);
arLatLong.push(arTemp);
}
return arLatLong;
},
fit_in_screen : function()
{
//Objetos de tipo maps.LatLng
var arLlObjects = this.extract_latlong_from_markers(null,true);
//bug(arLlObjects,"llobjects");
//Recuperamos los limites que se están visualizando
var oLlBound = new google.maps.LatLngBounds();
//Recorremos cada punto y lo pasamos por el metodo extend
for(var i = 0; i < arLlObjects.length; i++)
{
oLlBound.extend(arLlObjects[i]);
}
// Fit these bounds to the map
this.oMap.fitBounds(oLlBound);
},
//=======================================================================
oMap : null, //El objeto mapa
//Antes la llamaba initialize. Le he cambiado el nombre para demostrar
//que no necesariamente tiene que ser asi.
load_map: function()
{
//bug(this,"this en initialize"); //this aqui es document
//bug(this.gmap,"this gmap"); no existe
//el div donde se dibujara el mapa
var eDivContainer = document.getElementById(gmaps3.config.sIdDivContainer);
//objeto jquery del div contenedor. Es distinto del anterior ya que no puedo
//utilizar este mismo dentro del constructor "Map". este objeto me sirve
//para configurar sus estilos
var eDivCanvas = jQuery(eDivContainer);
if(gmaps3.config.sUnitWH=='px')
{
eDivCanvas.width(gmaps3.config.iWidth);
eDivCanvas.height(gmaps3.config.iHeight);
}
else
{
var sSize = gmaps3.config.iWidth + gmaps3.config.sUnitWH;
bug(sSize);
eDivCanvas.width(sSize);
sSize = gmaps3.config.iHeight + gmaps3.config.sUnitWH;
eDivCanvas.height(sSize);
}
eDivCanvas.css("margin", "0");
eDivCanvas.css("padding", "0");
//La zona a visualizar. Es un objeto latitud longitud el cual se utilizará
//para centrar el mapa.
var oLlCenter = new google.maps.LatLng(gmaps3.config.fLatitude, gmaps3.config.fLongitude);
var oConfig =
{
center: oLlCenter,
zoom: gmaps3.config.iZoom,
mapTypeId : gmaps3.get_maptype()
};
//bug(oConfig,"config");
gmaps3.oMap = new google.maps.Map(eDivContainer, oConfig);
//bug(gmaps3.oMap,"mapa recien construido");
gmaps3.draw_markers(gmaps3.config.arMarkers);
if(gmaps3.config.drawLines==true)
{
var arLatLong = gmaps3.extract_latlong_from_markers(gmaps3.config.arMarkers);
//bug(arLatLong,"arLatLong");
gmaps3.draw_lines(arLatLong);
}
//Reajusta la visualizacion de los marcadores
gmaps3.fit_in_screen();
//bug(gmaps3);
//gmaps3 = null; si hago esto no podria acceder a los marcadores al hacer click
//bug(gmaps3);
}
};
Autor: Eduardo A. F.
Publicado: 09-06-2012 17:56
Actualizado: 10-06-2012 17:35