Hack para Phoogle, abre los globos de información desde fuera del mapa
Phoogle es una fantástica clase para manejar la API de GoogleMaps y poder generar en unas cuantas lineas mapas simples y funcionales. El único problema podría ser la limitación que tiene a la hora de desarrollar nuevas operaciones.
Mi problema era que quería que, al pinchar en un enlace apareciera el globo de texto asociado mostrando la ubicación. Esta funcion la habia visto con la clase GoogleMapAPI.class.php y pensaba que Phoogle tambien lo podria hacer pero, vistos los ejemplos me di cuenta que no, asi que me puse manos a la obra para aplicar alguna pequeña mejora y poder realizarlo de una manera simple.
Para hacerlo he realizado unas pequeñas modificaciones.
En el archivo que podéis descargar de aquí, entramos y modificamos las siguientes lineas:
Despues de la linea 241, donde aparece:
-
echo " <script type=\"text/javascript\">\n";
insertamos esto:
En la que ahora será la linea 278, después de:
-
map.addOverlay(marker".$g.")\n
insertamos:
-
markers[".$g."] = marker".$g.";\n
Con esta modificacion podremos utilizar una nueva funcion javascript llamada click_sidebar(). A esta función le pasaremos 2 parámetros, el primero es el numero de "dirección" al que queremos llamar (la primera es 0, la segunda 1....). El segundo parámetro será el contenido del globo de información.
Ejemplo: <a href="#" onclick="javascript:click_sidebar('0', 'primer punto del mapa');return false;">texto del link</a>.
Lo mejor para despejar dudas será un ejemplo practico amplio..
Para el ejemplo usaremos 2 archivos que estarán en la misma parpeta dentro del servidor:
Archivo phogle.php (version Phoogle Maps 2.0) CON LA MODIFICACIÓN REALIZADA! más la función de obtención de APIKEY automatica:
-
<?php
-
-
/**
-
* Phoogle Maps 2.0 | Uses Google Maps API to create customizable maps
-
* that can be embedded on your website
-
* Copyright (C) 2005 Justin Johnson
-
*
-
* This program is free software; you can redistribute it and/or modify
-
* it under the terms of the GNU General Public License as published by
-
* the Free Software Foundation; either version 2 of the License, or
-
* (at your option) any later version.
-
*
-
* This program is distributed in the hope that it will be useful,
-
* but WITHOUT ANY WARRANTY; without even the implied warranty of
-
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-
* GNU General Public License for more details.
-
*
-
* You should have received a copy of the GNU General Public License
-
* along with this program; if not, write to the Free Software
-
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
*
-
*
-
* Phoogle Maps 2.0
-
* Uses Google Maps Mapping API to create customizable
-
* Google Maps that can be embedded on your website
-
*
-
* @class Phoogle Maps 2.0
-
* @author Justin Johnson <justinjohnson@system7designs.com>
-
* @copyright 2005 system7designs
-
*/
-
-
-
-
-
class PhoogleMap{
-
/**
-
* validPoints : array
-
* Holds addresses and HTML Messages for points that are valid (ie: have longitude and latitutde)
-
*/
-
/**
-
* invalidPoints : array
-
* Holds addresses and HTML Messages for points that are invalid (ie: don't have longitude and latitutde)
-
*/
-
/**
-
* mapWidth
-
* width of the Google Map, in pixels
-
*/
-
var $mapWidth = 300;
-
/**
-
* mapHeight
-
* height of the Google Map, in pixels
-
*/
-
var $mapHeight = 300;
-
-
/**
-
* apiKey
-
* Google API Key
-
*/
-
var $apiKey = "";
-
-
/**
-
* showControl
-
* True/False whether to show map controls or not
-
*/
-
var $showControl = true;
-
-
/**
-
* showType
-
* True/False whether to show map type controls or not
-
*/
-
var $showType = true;
-
/**
-
* controlType
-
* string: can be 'small' or 'large'
-
* display's either the large or the small controls on the map, small by default
-
*/
-
-
var $controlType = 'small';
-
-
/**
-
* zoomLevel
-
* int: 0-17
-
* set's the initial zoom level of the map
-
*/
-
-
var $zoomLevel = 4;
-
-
-
-
-
/**
-
* @function addGeoPoint
-
* @description Add's an address to be displayed on the Google Map using latitude/longitude
-
* early version of this function, considered experimental
-
*/
-
-
function addGeoPoint($lat,$long,$infoHTML){
-
$this->validPoints[$pointer]['lat'] = $lat;
-
$this->validPoints[$pointer]['long'] = $long;
-
$this->validPoints[$pointer]['htmlMessage'] = $infoHTML;
-
}
-
-
/**
-
* @function centerMap
-
* @description center's Google Map on a specific point
-
* (thus eliminating the need for two different show methods from version 1.0)
-
*/
-
-
function centerMap($lat,$long){
-
$this->centerMap = "map.centerAndZoom(new GPoint(".$long.",".$lat."), ".$this->zoomLevel.");\n";
-
}
-
-
-
/**
-
* @function addAddress
-
* @param $address:string
-
* @returns Boolean True:False (True if address has long/lat, false if it doesn't)
-
* @description Add's an address to be displayed on the Google Map
-
* (thus eliminating the need for two different show methods from version 1.0)
-
*/
-
function addAddress($address,$htmlMessage=null){
-
}
-
$apiURL = "http://maps.google.com/maps/geo?&output=xml&key=".$this->apiKey."&q=";
-
-
$this->invalidPoints[$pointer]['lat']= $results['kml'][Response]['Placemark']['Point']['coordinates'][0];
-
$this->invalidPoints[$pointer]['long']= $results['kml'][Response]['Placemark']['Point']['coordinates'][1];
-
$this->invalidPoints[$pointer]['passedAddress'] = $address;
-
$this->invalidPoints[$pointer]['htmlMessage'] = $htmlMessage;
-
}else{
-
$this->validPoints[$pointer]['lat']= $results['kml'][Response]['Placemark']['Point']['coordinates'];
-
$this->validPoints[$pointer]['long']= $results['kml'][Response]['Placemark']['Point']['coordinates'];
-
$this->validPoints[$pointer]['passedAddress'] = $address;
-
$this->validPoints[$pointer]['htmlMessage'] = $htmlMessage;
-
}
-
-
-
}
-
/**
-
* @function showValidPoints
-
* @param $displayType:string
-
* @param $css_id:string
-
* @returns nothing
-
* @description Displays either a table or a list of the address points that are valid.
-
* Mainly used for debugging but could be useful for showing a list of addresses
-
* on the map
-
*/
-
function showValidPoints($displayType,$css_id){
-
if ($displayType == "table"){
-
for ($t=0; $t<$total; $t++){
-
}
-
echo "</table>\n";
-
}
-
if ($displayType == "list"){
-
for ($lst=0; $lst<$total; $lst++){
-
}
-
echo "</ul>\n";
-
}
-
}
-
/**
-
* @function showInvalidPoints
-
* @param $displayType:string
-
* @param $css_id:string
-
* @returns nothing
-
* @description Displays either a table or a list of the address points that are invalid.
-
* Mainly used for debugging shows only the points that are NOT on the map
-
*/
-
function showInvalidPoints($displayType,$css_id){
-
if ($displayType == "table"){
-
for ($t=0; $t<$total; $t++){
-
}
-
echo "</table>\n";
-
}
-
if ($displayType == "list"){
-
for ($lst=0; $lst<$total; $lst++){
-
}
-
echo "</ul>\n";
-
}
-
}
-
/**
-
* @function setWidth
-
* @param $width:int
-
* @returns nothing
-
* @description Sets the width of the map to be displayed
-
*/
-
function setWidth($width){
-
$this->mapWidth = $width;
-
}
-
/**
-
* @function setHeight
-
* @param $height:int
-
* @returns nothing
-
* @description Sets the height of the map to be displayed
-
*/
-
function setHeight($height){
-
$this->mapHeight = $height;
-
}
-
/**
-
* @function setAPIkey
-
* @param $key:string
-
* @returns nothing
-
* @description Stores the API Key acquired from Google
-
*/
-
function setAPIkey($key){
-
$this->apiKey = $key;
-
}
-
/**
-
* @function printGoogleJS
-
* @returns nothing
-
* @description Adds the necessary Javascript for the Google Map to function
-
* should be called in between the html <head></head> tags
-
*/
-
function printGoogleJS(){
-
echo "\n<script src=\"http://maps.google.com/maps?file=api&v=2&key=".$this->apiKey."\" type=\"text/javascript\"></script>\n";
-
}
-
/**
-
* @function showMap
-
* @description Displays the Google Map on the page
-
*/
-
function showMap(){
-
echo "\n<div id=\"map\" style=\"width: ".$this->mapWidth."px; height: ".$this->mapHeight."px\">\n</div>\n";
-
echo " <script type=\"text/javascript\">\n";
-
echo "var markers = [];\n";
-
echo "function showmap(){
-
//<![CDATA[\n
-
if (GBrowserIsCompatible()) {\n
-
var map = new GMap(document.getElementById(\"map\"));\n";
-
echo "map.centerAndZoom(new GPoint(".$this->validPoints[0]['long'].",".$this->validPoints[0]['lat']."), ".$this->zoomLevel.");\n";
-
}else{
-
}
-
echo "}\n
-
var icon = new GIcon();
-
icon.image = \"http://labs.google.com/ridefinder/images/mm_20_red.png\";
-
icon.shadow = \"http://labs.google.com/ridefinder/images/mm_20_shadow.png\";
-
icon.iconSize = new GSize(12, 20);
-
icon.shadowSize = new GSize(22, 20);
-
icon.iconAnchor = new GPoint(6, 20);
-
icon.infoWindowAnchor = new GPoint(5, 1);
-
-
";
-
if ($this->showControl){
-
-
}
-
if ($this->showType){
-
echo "map.addControl(new GMapTypeControl());\n";
-
}
-
-
for ($g = 0; $g<$numPoints; $g++){
-
echo "var point".$g." = new GPoint(".$this->validPoints[$g]['long'].",".$this->validPoints[$g]['lat'].")\n;
-
var marker".$g." = new GMarker(point".$g.");\n
-
map.addOverlay(marker".$g.")\n
-
markers[".$g."] = marker".$g.";\n
-
GEvent.addListener(marker".$g.", \"click\", function() {\n";
-
if ($this->validPoints[$g]['htmlMessage']!=null){
-
}else{
-
}
-
echo "});\n";
-
}
-
echo " //]]>\n
-
}
-
window.onload = showmap;
-
</script>\n";
-
}
-
///////////THIS BLOCK OF CODE IS FROM Roger Veciana's CLASS (assoc_array2xml) OBTAINED FROM PHPCLASSES.ORG//////////////
-
function xml2array($xml){
-
$this->depth=-1;
-
return $this->arrays[0];
-
-
}
-
function startElement($parser, $name, $attrs){
-
$this->keys[]=$name;
-
$this->node_flag=1;
-
$this->depth++;
-
}
-
function characterData($parser,$data){
-
$this->arrays[$this->depth][$key]=$data;
-
$this->node_flag=0;
-
}
-
function endElement($parser, $name)
-
{
-
if($this->node_flag==1){
-
$this->arrays[$this->depth][$key]=$this->arrays[$this->depth+1];
-
}
-
$this->node_flag=1;
-
$this->depth--;
-
}
-
//////////////////END CODE FROM Roger Veciana's CLASS (assoc_array2xml) /////////////////////////////////
-
}//End Of Class
-
-
function gmaps_apikey($username, $password, $url=null){
-
-
// create cookie file temp
-
$postdata = 'Email='.$username.'&Passwd='.$password.'&GA3T=5AS_gBsvDHI&nui=15&'.'fpui=3&service=reader&ifr=true&askapache=lovesgoogle&rm=hide&itmpl=true&hl=en&alwf=true&continue=&null=Sign in';
-
-
$ch = curl_init("https://www.google.com/accounts/ServiceLoginBoxAuth");
-
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
-
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
-
curl_setopt ($ch, CURLOPT_COOKIEJAR, $google_cookie);
-
curl_setopt ($ch, CURLOPT_COOKIEFILE, $google_cookie);
-
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
-
curl_setopt ($ch, CURLOPT_POST, 1);
-
$askapache_curl_google_result = curl_exec ($ch);
-
curl_close($ch);
-
-
$ch = curl_init('http://maps.google.com/maps/api_signup?url='.$url);
-
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
-
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
-
curl_setopt ($ch, CURLOPT_COOKIEJAR, $google_cookie);
-
curl_setopt ($ch, CURLOPT_COOKIEFILE, $google_cookie);
-
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
-
curl_setopt ($ch, CURLOPT_POST, 1);
-
$askapache_curl_google_result = curl_exec ($ch);
-
curl_close($ch);
-
-
$ini = '<pre class="code">';
-
$fin = '</pre>';
-
$exp_info = '!'.$ini.'(.+)'.$fin.'!U';
-
return $out[1][0];
-
}
-
?>
Archivo index.php que contendrá el código del mapa. (contiene una función de apoyo para generar los mapas) :
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head>
-
<?
-
$direcciones = '';
-
function mapa($username, $password, $direccion, $alto="350", $ancho="100%"){
-
global $direcciones;
-
require_once 'phoogle.php';
-
$map = new PhoogleMap();
-
$map->setAPIKey(gmaps_apikey($username, $password));
-
$map->zoomLevel = 0; //zoom in as far as we can
-
$map->setWidth($ancho); //pixels
-
$map->setHeight($alto); //pixels
-
$map->controlType = 'large'; //show large controls on the side
-
$map->showType = false; //hide the map | sat | hybrid buttons
-
-
foreach($direccion as $key=>$value){
-
//generado de lsita de lugares
-
$direcciones .= '<a href="#" onclick="javascript:click_sidebar(\''.$key.'\', \''.$value['c'].'\');return false;">'.$value['t'].'</a><br>';
-
//generado de puntos en el mapa
-
$map->addAddress($value['dir'], $value['c']);
-
}
-
return $map;
-
}
-
// lista de lugares
-
'dir'=>'Palencia', //direccion a buscar para senialar en el mapa
-
't'=>'Ir a Palencia', //titulo del link
-
'c'=>'Ejemplo de texto para el<br> globo del punto en Palencia' //contenido del globo
-
),
-
'dir'=>'Madrid',
-
't'=>'Ir a Madrid',
-
'c'=>'Ejemplo de texto para el<br> globo del punto en Madrid'
-
),
-
'dir'=>'Burgos',
-
't'=>'Ir a Burgos',
-
'c'=>'Ejemplo de texto para el<br> globo del punto en Burgos'
-
),
-
'dir'=>'Elche',
-
't'=>'Ir a Elche',
-
'c'=>'Ejemplo de texto para el<br> globo del punto en Elche'
-
)
-
);
-
$map = mapa('AQUI_TU_CUENTA_DE_USUARIO@gmail.com', 'AQUI_TU_CONTRASENIA', $lugares);
-
$map->printGoogleJS();
-
?>
-
</head>
-
<body>
-
<?
-
$map->showMap(); //mostramos el mapa
-
?>
-
<!-- <h2>DEBUG</h2>
-
<h3>Direcciones validas:</h3>
-
<h4>(Mostradas en el mapa)</h4>
-
<? $map->showValidPoints("table","my_table"); ?>
-
<h3>Direcciones no validas</h3>
-
<h4>(Direcciones no mostradas en el mapa)</h4>
-
<? $map->showInvalidPoints("list","my_list"); ?>
-
-->
-
</body>
-
</html>
Una vez guardados los dos archivos (y corregidos los símbolos que están mal... ya sabéis lo de las " ' ") solo tenéis que entrar en el index.php para ver el resultado.
Muuy grosa la web, felicitaciones
Se ve muy interesante, pero
Hasta ahora me sale error:
“Parse error: syntax error, unexpected T_VARIABLE, expecting ‘)’ in path\demo2.php on line 49″
Como se ingresan las direcciones?(linea 6 de index.php)
Creo q ese puede ser el problema.
Gracias de antemano
Hola arkanhell, el error que tienes, lo tienes dentro del PHP, por eso te sale el error como texto HTML en la pagina. Las direcciones se insertan en un array, por lo que no se pueden poner comillas simples (las que están bajo la ?) si se hace eso, el código da error..
para insertar un texto en el array con ese tipo de comillas tienes que usar barra comilla
\'.El resto de errores supongo que serán parecidos. si sigue sucediendo escribenos también la linea del error y la linea antes.. seguramente este en una de las 2 el error..
Hola amigos estube leyendo lo que escribieron los Post y todas las indicaciones, pero no entiendo por que me marca el siguiente error.
Fatal error: Cannot use string offset as an array in C:\Program Files\VertrigoServ\www\phoogle.php on line 264
el codigo del index es el siguiente, deacuerdo a las modificaciones que habia que realizar..
setAPIKey(gmaps_apikey($username, $password));
$map->zoomLevel = 0; //zoom in as far as we can
$map->setWidth($ancho); //pixels
$map->setHeight($alto); //pixels
$map->controlType = ‘large’; //show large controls on the side
$map->showType = false; //hide the map | sat | hybrid buttons
foreach($direccion as $key=>$value){
//generado de lsita de lugares
$direcciones .= ‘‘.$value['t'].’‘;
//generado de puntos en el mapa
$map->addAddress($value['dir'], $value['c']);
}
return $map;
}
// lista de lugares
$lugares = array(
array(
“dir”=>”Palencia”, //direccion a buscar para senialar en el mapa
“t”=>”Ir a Palencia”, //titulo del link
“c”=>”Ejemplo de texto para el globo del punto en Palencia” //contenido del globo
),
array(
“dir”=>”Madrid”,
“t”=>”Ir a Madrid”,
“c”=>”Ejemplo de texto para el globo del punto en Madrid”
),
array(
“dir”=>”Burgos”,
“t”=>”Ir a Burgos”,
“c”=>”Ejemplo de texto para el globo del punto en Burgos”
),
array(
“dir”=>”Elche”,
“t”=>”Ir a Elche”,
“c”=>”Ejemplo de texto para el globo del punto en Elche”
)
);
$map = mapa(“fajardotobar@gmail.com”, “10913495″, $lugares);
$map->printGoogleJS();
?>
showMap(); //mostramos el mapa
echo $direcciones; //mostramos la lista de direcciones generada
?>
<!– DEBUG
Direcciones validas:
(Mostradas en el mapa)
showValidPoints(“table”,”my_table”); ?>
Direcciones no validas
(Direcciones no mostradas en el mapa)
showInvalidPoints(“list”,”my_list”); ?>
–>
saludos espero que me puedan ayudar..
hola Mr_Gom, pusiste el archivo phogle.php como se indica? usaste el código de ejemplo completo?
da la sensación de que en el código que enviaste no esta todas las lineas…
Si copie todas las lineas, bueno porfa ayuda esto es algo que me intereza mucho realizar.
setAPIKey(gmaps_apikey($username, $password));
$map->zoomLevel = 0; //zoom in as far as we can
$map->setWidth($ancho); //pixels
$map->setHeight($alto); //pixels
$map->controlType = ‘large’; //show large controls on the side
$map->showType = false; //hide the map | sat | hybrid buttons
foreach($direccion as $key=>$value){
//generado de lsita de lugares
$direcciones .= ‘‘.$value["t"].’‘;
//generado de puntos en el mapa
$map->addAddress($value['dir'], $value['c']);
}
return $map;
}
// lista de lugares
$lugares = array(
array(
“dir”=>”Palencia”, //direccion a buscar para senialar en el mapa
“t”=>”Ir a Palencia”, //titulo del link
“c”=>”Ejemplo de texto para el globo del punto en Palencia” //contenido del globo
),
array(
“dir”=>”Madrid”,
“t”=>”Ir a Madrid”,
“c”=>”Ejemplo de texto para el globo del punto en Madrid”
),
array(
“dir”=>”Burgos”,
“t”=>”Ir a Burgos”,
“c”=>”Ejemplo de texto para el globo del punto en Burgos”
),
array(
“dir”=>”Elche”,
“t”=>”Ir a Elche”,
“c”=>”Ejemplo de texto para el globo del punto en Elche”
)
);
$map = mapa(“fajardotobar@gmail.com”, “10913495″, $lugares);
$map->printGoogleJS();
?>
showMap(); //mostramos el mapa
echo $direcciones; //mostramos la lista de direcciones generada
?>
<!– DEBUG
Direcciones validas:
(Mostradas en el mapa)
showValidPoints(“table”,”my_table”); ?>
Direcciones no validas
(Direcciones no mostradas en el mapa)
showInvalidPoints(“list”,”my_list”); ?>
–>
Como Muesta en el phoogle se cae aca en esta funcion
function addAddress($address,$htmlMessage=null){
if (!is_string($address)){
die(“All Addresses must be passed as a string”);
}
$apiURL = “http://maps.google.com/maps/geo?&output=xml&key=”.$this->apiKey.”&q=”;
$addressData = file_get_contents($apiURL.urlencode($address));
$results = $this->xml2array(utf8_encode($addressData));
if (empty($results['kml'][Response]['Placemark']['Point']['coordinates'])){
$pointer = count($this->invalidPoints);
$this->invalidPoints[$pointer]['lat']= $results['kml'][Response]['Placemark']['Point']['coordinates'][0];
$this->invalidPoints[$pointer]['long']= $results['kml'][Response]['Placemark']['Point']['coordinates'][1];
$this->invalidPoints[$pointer]['passedAddress'] = $address;
$this->invalidPoints[$pointer]['htmlMessage'] = $htmlMessage;
}else{
$pointer = count($this->validPoints);
$this->validPoints[$pointer]['lat']= $results['kml'][Response]['Placemark']['Point']['coordinates'];
$this->validPoints[$pointer]['long']= $results['kml'][Response]['Placemark']['Point']['coordinates'];
$this->validPoints[$pointer]['passedAddress'] = $address;
$this->validPoints[$pointer]['htmlMessage'] = $htmlMessage;
}
}
y si se ve en el codigo puesto por ti es en la Linea 132, bueno ahi detalle mas mi problema saludos y de antemano muchas gracias..