Foros del Web » Programando para Internet » Javascript »

Cargar json con php en JS

Estas en el tema de Cargar json con php en JS en el foro de Javascript en Foros del Web. Buenas. Estoy intentando hacer un mapa de google maps para que me muestre los marcadores existentes en una base de datos que ya tengo hecha. ...
  #1 (permalink)  
Antiguo 29/03/2012, 04:00
 
Fecha de Ingreso: mayo-2010
Mensajes: 17
Antigüedad: 14 años
Puntos: 0
Cargar json con php en JS

Buenas.

Estoy intentando hacer un mapa de google maps para que me muestre los marcadores existentes en una base de datos que ya tengo hecha.

De momento puedo crear el fichero json con php de esta forma:

Código:
while ($row = @mysql_fetch_assoc($result)){
$data[$x] = array("lat" => $row['coordY'], "lng" => $row['coordX']);
$x++;
}
echo json_encode($data);
Por encima esta la conexion a la base de datos y la consulta de las coordenadas. Si ejecuto esto en el explorador de internet, obtengo lo siguiente:

[{"lat":"A","lng":"B"},{"lat":"C","lng":"D"},{"lat" :"E","lng":"F"}]

Ahora lo que quiero es poder usar este fichero desde javascript para crear los puntos en el mapa, pero no soy capaz de hacer que java script obtenga el array con los datos.

Mi idea era hacer algo asi:
Código:
function result(){
	var data = <?php phpsqlajax_genjson.php ?> //fichero que genera el json
	for (var i = 0;i < data.length; i += 1) {
        var lat = data[i].lat;
        var lon = data[i].lng;
        //var latlng = new GLatLng(lat, lng);
	//map.addOverlay(new GMarker(latlng, markerOptions));
Pero en la variable data no tengo nada. He probado alguna que otra forma, cargarlo antes de la funcion y tal pero nada. No tengo demasiada idea de javascript y no he encontrado ningun ejemplo en internet que muestre esto exactamente.

Confio en que sea una tonteria y el problema este en donde llamo a la variable y tal...

¿Alguna idea?
  #2 (permalink)  
Antiguo 29/03/2012, 09:02
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: Cargar json con php en JS

¡buenas!
¿en donde se encuentra definido el código javascript? ¿en un documento php o un archivo js? si se encuentra en un documento php, no veo por qué debes tener problema. asumiré en ese caso que:
· tienes una versión muy obsoleta de php de modo que no tiene el módulo json
· dudo mucho que php genere mal el contenido, pero igual revisa en la consola si ocurre alguna excepción (señal de error).

si el código esta aislado en un archivo *.js, entonces debes asegurarte que el servidor esté adecuadamente configurado para que también analice posible código php en dichos archivos.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #3 (permalink)  
Antiguo 29/03/2012, 09:22
 
Fecha de Ingreso: mayo-2010
Mensajes: 17
Antigüedad: 14 años
Puntos: 0
Respuesta: Cargar json con php en JS

Pues... el codigo javascript lo tengo en un fichero html que es el que carga la pagina.

Código:
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Mapa</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAuPsJpk3MBtDpJ4G8cqBnjRRaGTYH6UMl8mADNa0YKuWNNa8VNxQCzVBXTx2DYyXGsTOxpWhvIG7Djw" type="text/javascript"></script>
 
 <script type="text/javascript">

       
	 function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(A, B), 13);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());	
	  }
	}
    function result(){
		var data = <?php phpsqlajax_genjson.php ?> //fichero que genera el json
		for (var i = 0;i < data.length; i += 1) {
    	    var lat = data[i].lat;
        	var lon = data[i].lng;
        var latlng = new GLatLng(lat, lng);
		map.addOverlay(new GMarker(latlng, markerOptions));
      	}
	}

	
    </script>

<style type="text/css">
.mapaGoogle {
	width: 500px;
	height: 300px;
	float: left;
}
</style>
</head>

<body onLoad="initialize()" onUnload="GUnload()" style="font-family: Arial;border: 0 none;">
    
    <div id="map_canvas" class="mapaGoogle"></div>
</body>
</html>
Si quito la funcion de result, carga el mapa en las coordenadas que le pongas. Pero si pongo la funcion result, deja de cargarlo, no sale nada en la pantalla.

He probado a hacerlo por partes, olvidarme del google maps y que muestre un alert con el codigo json pasado por el fichero php pero tampoco hace nada.

Supongo que el problema esta en la linea donde llamo al fichero php, que no se debe hacer asi.

La version de php es la ultima creo, porque me he bajado el xampp para probarlo y viene actualizado. De todas formas, ejecutando solo el fichero de php, este me crea un fichero json sin problemas.

Por otro lado, con el codigo que he puesto en este mensaje, no se donde deberia llamar a la funcion result para que me añada los marcadores. Me gustaria que la llamase cada cierto tiempo para que se fuesen actualizando dinamicamente sin cargar el mapa de nuevo.

Creo que seria algo asi:
Código:
var marcadores = setInterval('result()',1000);
Pero no se si lo tengo que poner dentro de los <scripts> </script> o en el body... Bueno, esto me preocupa menos, si consiguiese que mostrase los marcadores me vale por el momento.
  #4 (permalink)  
Antiguo 30/03/2012, 07:33
 
Fecha de Ingreso: mayo-2010
Mensajes: 17
Antigüedad: 14 años
Puntos: 0
Respuesta: Cargar json con php en JS

he conseguido que me cargue los marcadores desde el fichero json. Encontre un ejemplo en internet y lo he medio adaptado a lo mio para poder entenderlo. Aun tengo que hacer mas cambios pero sin tocar casi nada, esto me "funciona":

Código:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAPDUET0Qt7p2VcSk6JNU1sBSM5jMcmVqUpI7aqV44cW1cEECiThQYkcZUPRJn9vy_TWxWvuLoOfSFBw" type="text/javascript"></script>
    
    <style type="text/css">
.box {
    margin: 10px;
    padding: 10px;
    width: 180px;
    border: 1px solid #78BA91;
    text-align: center;
    background: #fff;
}

.mapaGoogle {
	width: 500px;
	height: 300px;
	float: left;
}
.periodical {
  border-color: #E79D35;
  float: right;
}

#periode {
    width: 30px;
    border: 1px solid #000;
    text-align: center;
}
</style>
  </head>
  <body onunload="GUnload()">

    <!-- you can use tables or divs for the overall layout -->
    <table border=1>
      <tr>
        <td>
           <div id="map" class="mapaGoogle"></div>
        </td>
        
      </tr>
    </table>
  


    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>


    <script type="text/javascript">
    //<![CDATA[
    if (GBrowserIsCompatible()) {
      // Display the map, with some controls
     // var map = new GMap(document.getElementById("map"));
	  var map = new google.maps.Map(document.getElementById("map"));  //esta declaracion o la de arriba, no se la diferencia
	  map.addControl(new GSmallMapControl());
     // map.addControl(new GLargeMapControl()); //Quitado porque genera doble los botones de zoom y desplazamiento
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(43.4669443349282,-3.862788677215576),9);
   
      // arrays to hold copies of the markers and html used by the side_bar
      // because the function closure trick doesnt work there
     // var side_bar_html = "";
     // var gmarkers = [];
     // var htmls = [];
     // var i = 0;

      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point);
       // GEvent.addListener(marker, "click", function() {
       //   marker.openInfoWindowHtml(html);
       // });
        // save the info we need to use later for the side_bar
        //gmarkers[i] = marker;
        //htmls[i] = html;
        // add a line to the side_bar html
        //side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br>';
        //i++;
        return marker;
      }

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
      }

      // ================================================================
      // === Define the function thats going to process the JSON file ===
      process_it = function(doc) {
        // === Parse the JSON document === 
        var jsonData = eval('(' + doc + ')');
        
        // === Plot the markers ===
        for (var i=0; i<jsonData.markers.length; i++) {
          var point = new GLatLng(jsonData.markers[i].lat, jsonData.markers[i].lng);
          var marker = createMarker(point, jsonData.markers[i].label, jsonData.markers[i].html);
          map.addOverlay(marker);
        }

        // put the assembled side_bar_html contents into the side_bar div
      //  document.getElementById("side_bar").innerHTML = side_bar_html;

        // === Plot the polylines ===
        for (var i=0; i<jsonData.lines.length; i++) { //Puedo hacer otra tabla con las coordenadas de las polilineas y meterlas en el mismo json, asi las cogeria de ahi y listo.
          var pts = [];
          for (var j=0; j<jsonData.lines[i].points.length; j++) {
            pts[j] = new GLatLng(jsonData.lines[i].points[j].lat, jsonData.lines[i].points[j].lng);
          }
          map.addOverlay(new GPolyline(pts, jsonData.lines[i].colour, jsonData.lines[i].width)); 
        }
      }          
      
      // ================================================================
      // === Fetch the JSON data file ====    
      GDownloadUrl("phpsqlajax_genjson.php", process_it);
      // ================================================================

    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    // This Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/   
    // http://econym.org.uk/gmap/

    //]]>
    </script>
  </body>

</html>
Pongo lo de "funciona" entre comillas porque no consigo que se refresquen los marcadores sin recargar el mapa completo.

Creo que deberia usar la funcion periodical(X) siendo X el tiempo que quiero que espere entre refresco y refresco. Pero no se a que tengo que aplicar esa funcion. Tambien he visto algo sobre esta otra funcion: self.setInterval ("funcionARepetir()", 4000); Pero estoy en las mismas, no se a que...

¿Alguna idea?

Última edición por Biribu; 30/03/2012 a las 07:45

Etiquetas: ajax, funcion, js, json, php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:32.