jeudi 2 septembre 2010

Google Map à partir de XML

Lors d’un projet j’ai eu l’occasion d’intégrer Google Map dans une application web.Le but de visualiser la dispersion des élèves d’une école dans le monde.

Les étapes à faire :
1. Interroger le service Geocoder de Google afin d’obtenir les coordonnées de chaque pays.Je crée une classe nommée Geocodeur avec une méthode static et publique qui permet d’obtenir latitude et longitude d’un pays.
using System.Net;
public class Geocodeur
{
         private static string _googleUri = “http://maps.google.com/maps/geo?q=”;
         // [CLE] est une clé propre à un domain obtenu en s’inscrivant sur Google 

         //http://code.google.com/intl/fr/apis/maps/signup.html
        private static string _googlekey = [CLE];
       private const string _output = "csv";      


      // Constituer l'url pour intérroger le service geocodeur de Google
      private static string getGeocodeUri(string adresse)
 {
           adresse = HttpUtility.UrlEncode(adresse);
           return string.Format("{0}{1}&output={2}&key={3}",_googleUri,adresse,_output,_googlekey);
    }
   // Intérroger le service de geocodeur de Google
    public static string getCoordonne(string adresse)
{
       WebClient client = new WebClient();
      string uri = getGeocodeUri(adresse);
     byte[] datageo= client.DownloadData(uri);
     return System.Text.Encoding.ASCII.GetString(datageo);
    }

    public Geocodeur()
 {
     }
}

String strCoordonne = Geocodeur.getCoordonne(“France”);
String strLat = strCoordonne.Split(',')[2];
String strLng = strCoordonne.Split(',')[3];

2. Enregistrer ensuite ces coordonnées avec les informations à afficher pour chaque pays dans un fichier xml.
Le fichier possède la structure ci-dessous:

 
3. Créer une page html qui héberge le Google map. 4. Dans le fichier javascript Geo.js, je charge le fichier xml créé précédemment :
// Pour savoir si navigateur est ie6

var is_ie6 = ( window.external && typeof window.XMLHttpRequest == "undefined");
var iconeGrande = new GIcon();
iconeGrande.image = 'iconeGrande.png';

// Résoudre le problème IE6 qui ne supporte pas l'image png avec transparent
if(is_ie6){ iconeGrande.image = 'iconeGrande.gif';}
iconeGrande.shadow = null;i
coneGrande.iconSize = new GSize(48, 48);
iconeGrande.shadowSize = null;
iconeGrande.iconAnchor = new GPoint(24,24);
iconeGrande.infoWindowAnchor = new GPoint(24,24);
var iconePetite = new GIcon();

iconePetite.image = 'iconePetite.png';

if(is_ie6){ iconePetite.image = 'iconePetite.gif';}
iconePetite.shadow = null;
iconePetite.iconSize = new GSize(32, 32);
iconePetite.shadowSize = null;
iconePetite.iconAnchor = new GPoint(16,16);
iconePetite.infoWindowAnchor = new GPoint(16,16);
var map;

var xml;

function initialiserGoogleMap(langue)
{
       map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(33.8869170,9.5374990), 2, G_NORMAL_MAP);
      map.addControl(new GLargeMapControl());
      GDownloadUrl("geolocalisation.xml", function(data,responseCode)
{
        if(responseCode == 200) { xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marqueur");
       for (var i = 0; i < markers.length; i++)
       {
            var icone;
            var id = markers[i].getAttribute("id");
           // Si la France, on utilise grande icone
          if(id == '1') { icone = iconeGrande; }
         else { icone = iconePetite; }

         var information;
         if(langue == "fr")  {
              information = markers[i].getAttribute("informationFr");
         }
        else  {
              information = markers[i].getAttribute("informationEn");
         }

        var nombre = markers[i].getAttribute("nombre");
        var point = new GLatLng(parseFloat(markers[i].getAttribute("latitude"))
                      , parseFloat(markers[i].getAttribute  ("longitude")));
         var marker = createMarker(point, nombre,information, icone);
         map.addOverlay(marker);
    }
}
else {

  alert ('Erreur');
}
});
}

function createMarker(point, nombre, information,icone){
         var marker = new GMarker(point, icone); 

         var html = information;
GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html, {beakOffset:03}); });
        return marker;
}