In this example the Seminario II sutdents were asked to design a web page that display a Google map with earthquake information from the US Geological Survey USGS.
Camilo Vera solution can be found here (gracias Camilo).
Camilo’s php script is as follows:
<?php
//header("Content-type= application/json");
$xml =simplexml_load_file("http://earthquakes.usgs.gov/earthquakes/catalogs/1day-M2.5.xml");
$i=0;
//se recorren todos los nodos "entry"
foreach($xml->entry as $node){
//se recuperan los datos que tiene un namespace especificado por la siguiente url
$geo = $node->children("http://www.georss.org/georss");
$json[$i][0]=$geo->point;
$json[$i][1]=$node->title;
$i++;
}
print(json_encode($json));
?>
The javascript is as follows:
function initialize() {
myLatlng = new google.maps.LatLng(-33.04299, -71.586657);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
//se crea una instancia de un mapa de google
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var request = crear_XmlHttpRequest();
request.open("GET", "Conector.php", true);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
var yw_json = request.responseText;
//dirty JSON evaluation
var yw = eval('(' + yw_json + ')');
var i;
//se recorren el arreglo que contiene la informacion de las coordenadas y el nombre
//del lugar donde ocurrio el terremoto
for(i in yw){
//la tercera dimension del arreglo es inutil, pero lamentablemente json_encode de php lo crea
//se separan los dos puntos que determinan la coordenada
coordenadas = yw[i][0][0].split(" ");
//se guarda el nombre del lugar donde ocurrio el evento
lugar = yw[i][1][0];
//se crea el marcador en el mapa
myLatlng = new google.maps.LatLng(coordenadas[0], coordenadas[1]);
new google.maps.Marker({
position: myLatlng,
map: map,
title:lugar
});
}
}
}
request.send(null);
}
//Se define una funcion que retorne el objeto XMLHttpRequest dado que en la
//version 3 de la api de google se quito la clase GXmlHttp
function crear_XmlHttpRequest(){
var httpRequest;
if (window.XMLHttpRequest){
//El explorador implementa la interfaz de forma nativa
httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject){
//El explorador permite crear objetos ActiveX
try {
httpRequest = new ActiveXObject("MSXML2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!httpRequest){
alert("No ha sido posible crear una instancia de XMLHttpRequest");
}
return httpRequest;
}
The Html file is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="ajax_map.js"></script>
<title></title>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Alejandro Homes solution can be found here (gracias Alejandro). In this example the students used a php script as middle man to by pass the cross-domain restriction in web browsers.
The php script goes as follows:
<?php
//First send the corresponding headers
header("Content-type= application/json");
//get the XML data from the URL
$xml = simplexml_load_file("http://earthquake.usgs.gov/earthquakes/catalogs/1day-M2.5.xml");
$count=0;
//traverse the SimpleXML object and store in a associative array
foreach( $xml->entry as $entry )
{
$aeo = $entry->children("http://www.georss.org/georss");
$arr[$count] = array ('nombre'=>$entry->title,'fecha'=>$entry->updated,'geo_point'=>$aeo->point,'geo_elev'=>$aeo->elev);
$count++;
}
//JSON enconde and print
print(json_encode($arr));
?>
The html page is as follows:
<!DOCTYPE html "-//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">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAw0DAzQTTbMAlKOPlgYZyaxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxT4oLUvcIuwHQ71styNxZCnK2iqoQ"
type="text/javascript"></script>
<script type="text/javascript">
function reFresh() {
location.reload(true)
}
function initialize() {
if (GBrowserIsCompatible()) {
function setMarker( punto, texto){
var marker = new GMarker(punto, {draggable: false});
GEvent.addListener(marker, "click", function(){
// create the Google version of XMLHttpRequest object
marker.openInfoWindowHtml(texto);
});
map.addOverlay(marker);
}
var map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(-15,0);
map.setCenter(center, 1);
var request = GXmlHttp.create();
request.open("GET", "usgs.php", true);
request.onreadystatechange = function()
{
if(request.readyState == 4 && request.status == 200){
var eq_json = request.responseText;
var eq = eval('(' + eq_json + ')');
var i;
for(i in eq)
{
var lat_lng = eq[i].geo_point[0].split(" ");
var titulo = eq[i].nombre[0].split(",");
var magnitud = titulo[0].split(" ");
var xhtml = "lugar = " + titulo[1] + ", " + titulo[2] + "<br />";
xhtml += "magnitud = " + magnitud[1] + "° Richter<br />";
xhtml += "fecha = " + eq[i].fecha[0] + "<br />";
xhtml += "elevación = " + eq[i].geo_elev[0]/1000 + " [Km]<br />";
xhtml += "posición = " + eq[i].geo_point[0] + "<br />";
var point = new GLatLng(lat_lng[0],lat_lng[1]);
setMarker(point, xhtml);
}
//end for
}
}
request.send(null);
}
window.setInterval("reFresh()",60000); //recarga la pag cada 1 minuto
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 700px; height:550px"></div>
</body>
</html>
