Subversion Repositories eFlore/Applications.moissonnage

Rev

Rev 7 | Rev 31 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

// Javascript Document


// ==============================================================
//  FONCTIONS ADDITIONNELLES POUR GERER LES URLS
function convertirEnParametresUrl(objet) {
        var parametresUrl = '';
        for (attribut in objet) {
                if (typeof(objet[attribut]) == 'function' || typeof(objet[attribut]) == 'undefined' ||
                        objet[attribut] == null)
                        continue;
                parametresUrl += (parametresUrl == '' ? '' : '&') + attribut + "=" + objet[attribut].toString();
        }
        return parametresUrl;
};

function estParametreDansUrl(nomParametre) {
        var estDansUrl = false;
        var listeParametres = location.search.substring(1).split("&");
        for (var index = 0; index < listeParametres.length; index ++) {
                var split = listeParametres[index].split("=");
                if (split[0] == nomParametre) {
                        estDansUrl = true;
                }
        }
        return estDansUrl;
};

// =============================================================



var map = null,
optionsCoucheOSM = {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,'
        + ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 18
},
optionsCoucheGoogle = {
        attribution: 'Map data &copy;' + new Date().getFullYear() + ' <a href="http://maps.google.com">Google</a>',
        maxZoom: 18
},
coucheOSM = new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        optionsCoucheOSM),
couchePlanGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
        optionsCoucheGoogle),
coucheSatelliteGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}",
        optionsCoucheGoogle),
optionsCarte = {
        center : new L.LatLng(46, 2),
        zoom : 6,
        minZoom : 3,
        maxBounds : [[-85.051129, -180], [85.051129, 180]],
        layers : [couchePlanGoogle]
},
legende = null,
infoBulle = null;

var coucheSites = new L.FeatureGroup(),
overlays = [];

var requeteChargementPoints = null,
doitRafraichirCarte = true,
timer = null,
url = '';




$(document).ready(function() {
        initialiserWidget();
});

function initialiserWidget() {
        initialiserCarte();
        initialiserListeners();
        initialiserPanneauControle();
        chargerLimitesCommunales();
        if (!estParametreDansUrl('source')) {
                initialiserSources();
        }
        programmerRafraichissementCarte();
}

$(window).resize(function() {
        dimensionnerCarte();
        if (infoBulle != null) {
                redimensionnerPopup();
        }
});


function dimensionnerCarte() {
        $('#map').height($(window).height());
        $('#map').width($(window).width());
}

function initialiserCarte() {
        dimensionnerCarte();
        map = L.map('map', optionsCarte);
        coucheSites.addTo(map);
        coucheOSM.addTo(map);
        couchePlanGoogle.addTo(map);
        coucheSatelliteGoogle.addTo(map);
        var echelle = new L.Control.Scale({
                maxWidth : 100,
                metric : true,
                imperial : false,
                updateWhenIdle : true
        });
        map.addControl(echelle);
}
function initialiserListeners() {
        map.on('moveend', surChangementVueSurCarte);
        map.on('zoomend', surChangementVueSurCarte);
        map.on('popupclose', function(e) {
                masquerInfoBulle();
                programmerRafraichissementCarte();
        });
}

function initialiserPanneauControle() {
        var baseMaps = {
                "OSM" : coucheOSM,
                "Plan" : couchePlanGoogle,
                "Satellite" : coucheSatelliteGoogle
        };

        var overlayMaps = {};
        if (!estParametreDansUrl('source')) {
                for (var index = 0; index < nomSources.length; index ++) {
                        overlayMaps[nomSources[index]] = new L.LayerGroup();
                }
        }
        L.control.layers(baseMaps, overlayMaps).addTo(map);
        coucheOSM.bringToBack();
        couchePlanGoogle.bringToFront();
        coucheSatelliteGoogle.bringToBack();
        
        // garder par defaut la couche plan google comme selectionnee dans le panel
        var selecteursFonds = $('.leaflet-control-layers-base .leaflet-control-layers-selector');
        selecteursFonds[0].checked = false;
        selecteursFonds[1].checked = true;
        selecteursFonds[2].checked = false;
}

function chargerLimitesCommunales() {
        if (urlsLimitesCommunales != null) {
                for (var index = 0; index < urlsLimitesCommunales.length; index ++) {
                        var url = urlsLimitesCommunales[index];
                        var coucheDepartement = new L.KML(url, {async: true});
                        coucheDepartement.on("loaded", function(e) {
                                map.fitBounds(e.target.getBounds());
                        });
                        map.addLayer(coucheDepartement);
                }
        }
}

function initialiserSources() {
        overlays = $('.leaflet-control-layers-overlays .leaflet-control-layers-selector');
        $.each(overlays, function (index, input) {
                input.value = sources[index];
                input.id = 'overlay' + (index+1);
                var lien = '<a href="' + liensVersSources[index] + '" target="_blank">' + nomSources[index] + '</a>';
                $('#overlay' + (index+1) + ' ~ span').html(lien);
                input.type = 'radio';
                input.checked = (sources[index] == source);
                input.onchange = function(event) {
                        // evenement sur selection/deselection overlay dans sa checkbox
                        changerSource(event.target.value);
                }
        });
}

function surChangementVueSurCarte() {
        if (doitRafraichirCarte == false) {
                doitRafraichirCarte = true;
        } else {
                programmerRafraichissementCarte();
        }
}

function programmerRafraichissementCarte() {
        if(timer != null) {
        window.clearTimeout(timer);
    }
        if(requeteChargementPoints != null) {
                requeteChargementPoints.abort();
                requeteChargementPoints = null;
        }
        timer = window.setTimeout(function() {
                supprimerLocalisations();
                afficherMessageChargement('stations');
                chargerLocalisations();
    }, 400);
}


function supprimerLocalisations() {
        coucheSites.clearLayers();
}


function changerSource(projetClique) {
        // deselctionner les autres boutons des controles d'overlays dans le panel
        for (var index = 0; index < overlays.length; index ++) {
                if (overlays[index].value != projetClique) {
                        overlays[index].checked = false;
                }
        }
        // afficher les sites dans la carte pour le projet selectionne
        if (infoBulle != null) {
                masquerInfoBulle();
        }
        source = projetClique;
        programmerRafraichissementCarte();
}


function afficherMessageChargement(element) {
        var divTmplElement = 'tpl-chargement-' + element;
        $("#zone-chargement").append($("#" + divTmplElement).text());
        $("#zone-chargement").css('display', 'block');
}

function masquerMessageChargement() {
        $("#zone-chargement").css('display', 'none');
        $("#zone-chargement").children().remove();
}


// execution d'une requete AJAX
function executerAJAX() {
        if (requeteEnCours()) {
                masquerMessageChargement();
                requeteChargementPoints.abort();
        }
        requeteChargementPoints = $.getJSON(url).complete(function() {
                fonctionCallback();
        });
}

function requeteEnCours() {
        return (requeteChargementPoints != null && requeteChargementPoints.readyState != 4);
}

function retourRequeteOK() {
        return ((requeteChargementPoints.status == 200 || requeteChargementPoints.status == 304)
                || requeteChargementPoints.status == 0);
}



function chargerLocalisations() {
        // generer l'URL du script a interroger sur le serveur
        var coordonneesBordure = calculerCoordonneesBordure();
        var parametres = {
                "source" : source,
                "num_taxon" : num_taxon,
                "referentiel" : referentiel,
                "dept" : dept,
                "auteur" : auteur,
                "bbox" : coordonneesBordure,
                "zoom" : map.getZoom()
        };
        url = urlBase + "stations?" + convertirEnParametresUrl(parametres);
        
        fonctionCallback = traiterDonneesStations;
        executerAJAX();
}

function calculerCoordonneesBordure() {
        var bordure = map.getBounds();
        var ouest = bordure.getSouthWest().lng,
                sud = Math.max(bordure.getSouthWest().lat, -85.051129),
                est = bordure.getNorthEast().lng,
                nord = Math.min(bordure.getNorthEast().lat, 85.051129);
        // appliquer les limites possibles de la projection actuellement utilisee aux coordonnees
        // longitudes ouest et est de la bbox (permettra d'eviter de renvoyer des messages d'erreur)
        if (ouest < -180) {
                ouest += 360;
        } else if (ouest > 180) {
                ouest -= 360;
        }
        if (est < -180) {
                est += 360;
        } else if (est > 180) {
                est -= 360;
        }
        return [ouest, sud, est, nord].join(',');
}

function traiterDonneesStations() {
        masquerMessageChargement();
        
        var texte = requeteChargementPoints.responseText;
        if (!retourRequeteOK()) {
                alert(texte);
        } else {
                var donneesJSON = eval("(function(){return " + texte + ";})()");
                if (typeof(donneesJSON) != 'undefined' && typeof(donneesJSON.features) != 'undefined') {
                        ajouterObjets(donneesJSON);
                }
        }
}


function ajouterObjets(data) {
        coucheSites.clearLayers();
        var contientMailles = (data.features[0].properties.typeSite == 'MAILLE');
        for (var index = 0; index < data.features.length; index ++) {
                switch (data.features[index].properties.typeSite) {
                        case 'MAILLE'  : ajouterMaille(data.features[index]);
                                break;
                        case 'COMMUNE' :
                        case 'STATION' : ajouterPoint(data.features[index]);
                                break;
                }
        }
        if (contientMailles && legende == null) {
                afficherLegende();
        } else if (legende != null) {
                masquerLegende();
        }
}

function ajouterMaille(feature) {
        var coordonnees = [];
        for (var i = 0; i < feature.geometry.coordinates.length; i++) {
                var sommet = new L.LatLng(feature.geometry.coordinates[i][0], feature.geometry.coordinates[i][1]);
                coordonnees.push(sommet);
        }
        
        var objet = new L.Polygon(coordonnees, {
                color: '#FFFFFF',
                opacity : 0.7,
                weight: 1,
                fillColor : getColor(feature.properties.nombrePoints),
                fillOpacity : 0.6
        });
        objet.typeSite = feature.properties.typeSite;
        objet.nombrePoints = feature.properties.nombrePoints;
        objet.on('click', clicSurMaille);
        coucheSites.addLayer(objet);
        // afficher le nombre de points inclus dans la maille
        afficherNombreStationsDansMaille(objet);
}

function afficherNombreStationsDansMaille(maille) {
        // comme la div qui contiendra la valeur du nombre de stations va se placer dans la page
        // au centre de la maille (et qui va servir de point d'ancrage pour le bord gauche par defaut)
        // il est necessaire de creer un decalage vers la gauche en fonction du nombre de chiffres
        var decalage = calculerDecalagePositionnementNombre(maille.nombrePoints);
        var sudMaille    = maille._originalPoints[0].y,
                ouestMaille  = maille._originalPoints[0].x,
                nordMaille   = maille._originalPoints[2].y,
                estMaille    = maille._originalPoints[2].x,
                centreMaille = new L.Point((ouestMaille+estMaille)/2 - decalage, (sudMaille+nordMaille)/2);     
        var divIcon = new L.divIcon({
                className : "nombre-sites",
                html : maille.nombrePoints
        });
        var marqueurDiv = new L.Marker(map.layerPointToLatLng(centreMaille), {
                icon : divIcon,
                maille : maille.getBounds()
        });
        marqueurDiv.on('click', clicSurMaille);
        coucheSites.addLayer(marqueurDiv);
}

function calculerDecalagePositionnementNombre(nombrePoints) {
        var recul = 0;
        if (nombrePoints >= 10000) {
                recul = 14;
        } else if (nombrePoints >= 1000) {
                recul = 9;
        } else if (nombrePoints >= 100) {
                recul = 5;
        }
        return recul;
}

function clicSurMaille(event) {
        if (event.target._zIndex != null) {
                map.fitBounds(event.target.options.maille)
        } else {
                map.fitBounds(event.target.getBounds());
        }
}

// generer la couleur a afficher pour les mailles
function getColor(nombrePoints) {
        var couleur = {'bleu': 231, 'vert': 224, 'rouge': 64},
                seuils = [1, 10, 50 ,100, 500, 1000, 2500],
                pas = 26,
                position = 0;
        for (var index = 1; index < seuils.length-1 && nombrePoints >= seuils[index]; index ++) {
                position ++;
        }
        couleur.vert -= position*pas;
        return 'rgb('+couleur.bleu+','+couleur.vert+','+couleur.rouge+')';
        
        /*var codeHexa = 'rgb(231,224,64)';
        if (nombrePoints >= 2500) {
                codeHexa =  'rgb(231,68,64)';
        } else if (nombrePoints >= 1000) {
                codeHexa =  'rgb(231,94,64)';
        } else if (nombrePoints >= 500) {
                codeHexa =  'rgb(231,120,64)';
        } else if (nombrePoints >= 100) {
                codeHexa =  'rgb(231,146,64)';
        } else if (nombrePoints >= 50) {
                codeHexa =  'rgb(231,172,64)';
        } else if (nombrePoints >= 10) {
                codeHexa =  'rgb(231,198,64)';
        }
        return codeHexa;*/
}


function ajouterPoint(feature) {
        var iconePoint = new L.Icon({ iconUrl : pointImageUrl,   iconSize : [16, 16] }),
                iconeCommune   = new L.Icon({ iconUrl : communeImageUrl, iconSize : [24, 32] }),
                icone = (feature.properties.typeSite == 'STATION') ? iconePoint : iconeCommune,
                point = new L.LatLng(feature.geometry.coordinates[0], feature.geometry.coordinates[1]),
                marker = new L.Marker(point, {
                        icon : icone,
                        type : feature.properties.typeSite,
                        title : feature.properties.nom
                }).addTo(map);
        marker.on('click', surClicMarqueur);
        coucheSites.addLayer(marker);
}


function afficherLegende() {
        legende = new L.Control({position : 'bottomright'});
        legende.onAdd = function(map) {
                return construireContenuHtmlLegende();
        };
        map.addControl(legende);
}

function construireContenuHtmlLegende() {
        var div = L.DomUtil.create('div', 'info');
        div.innerHTML = '<h4>' + titreLegende + '</h4>';
        var seuils = [1, 10, 50 ,100, 500, 1000, 2500];
        var labels = [];
        for (var i = 0; i < seuils.length; i ++) {
                div.innerHTML += 
                        '<div class="legend">'+
                                '<span style="background:' + getColor(seuils[i] + 1) + '"></span>'+
                                seuils[i]+ (i + 1 < seuils.length ? '&ndash;' + seuils[i + 1] : '+')+
                        '</div>';
        }
        return div;
}

function masquerLegende() {
        map.removeControl(legende);
        legende = null;
}



function surClicMarqueur(event) {
        var latitude = event.target.getLatLng().lat;
        var longitude = event.target.getLatLng().lng;
        pointClique = event.target;
        afficherMessageChargement('observations');
        var parametres = {
                "source" : source,
                "num_taxon" : num_taxon,
                "referentiel" : referentiel,
                "auteur" : auteur,
                "longitude" : longitude,
                "latitude" : latitude
        };
        url = urlBase + "observations?" + convertirEnParametresUrl(parametres);
        fonctionCallback = traiterDonneesObservations;
        executerAJAX();
}

function traiterDonneesObservations() {
        masquerMessageChargement();
        var texte = requeteChargementPoints.responseText;
        if (!retourRequeteOK()) {
                alert(texte);
        } else {
                
                obsJSON = eval("(function(){return " + texte + ";})()");
                viderListeObservations();
                if (obsJSON.total > 0) {
                        doitRafraichirCarte = false;
                        map.setView(new L.LatLng(pointClique.getLatLng().lat, pointClique.getLatLng().lng), map.getZoom());
                        afficherInfoBulle();
                } else if (infoBulle != null)  {
                        masquerInfoBulle();
                }
        }
}

function viderListeObservations() {
        obsStation = new Array();
}


// ====================================================================
//  Gestion de l'infobulle

var obsJSON = null,
        pointClique = null,
        obsStation = [],
        typeAffichage = "";

function afficherInfoBulle() {
        var latitude = pointClique.getLatLng().lat;
        var longitude = pointClique.getLatLng().lng;
        infoBulle = new L.Popup({maxWidth : definirLargeurInfoBulle(), maxHeight : 350});
        infoBulle.setLatLng(new L.LatLng(latitude, longitude));
        infoBulle.setContent($("#tpl-obs").html());
        infoBulle.openOn(map);  
        remplirContenuPopup();
}

function definirLargeurInfoBulle() {
        var largeurViewPort = $(window).width();
        var lageurInfoBulle = null;
        if (largeurViewPort < 800) {
                largeurInfoBulle = 400;
        } else if (largeurViewPort >= 800 && largeurViewPort < 1200) {
                largeurInfoBulle = 500;
        } else if (largeurViewPort >= 1200) {
                largeurInfoBulle = 600;
        }
        return largeurInfoBulle;
}

function redimensionnerPopup() {
        $('.leaflet-popup-content*').css('width',  definirLargeurInfoBulle());
        $('#info-bulle').css('width',  definirLargeurInfoBulle());
}

function remplirContenuPopup() {
        ajouterTableauTriable("#obs-tableau");
        ajouterTitre();
        afficherOnglets();
        afficherTexteStationId();
}

function masquerInfoBulle() {
        if (map.hasLayer(infoBulle) && infoBulle != null) {
                map.removeLayer(infoBulle);
        }
        infoBulle = null;
}

function ajouterTitre() {
        var texteStationTitre = obsJSON.total + ' observation' + (obsJSON.total > 1 ? 's' : '')
                + ' pour ' + (pointClique.options.type=='STATION' ? 'la station : ' : 'la commune : ')
                + pointClique.options.title;
        $('#obs-station-titre').text(texteStationTitre);
}

function selectionnerOnglet() {
        $("#obs-vue-" + typeAffichage).css("display", "block");
        $('#obs-tableau-lignes').empty();
        $('#obs-liste-lignes').empty();
        if (typeAffichage=='liste') {
                $("#obs-vue-tableau").css("display", "none");
        } else {
                $("#obs-vue-liste").css("display", "none");
        }
}

function ajouterObservationsDansHTML() {
        if (obsStation.length==0) {
                // premiere execution de la fonction : faire une copie des objets JSON decrivant les observations 
                for (var index = 0; index < obsJSON.observations.length; index ++) {
                        obsStation.push(obsJSON.observations[index]);
                }
        }
        // ajouter les observations dans le code HTML
        var obsPage = [];
        for (var index = 0; index < obsStation.length; index ++) {
                obsPage.push(obsStation[index]);
        }
        $("#tpl-obs-"+typeAffichage).tmpl(obsPage).appendTo("#obs-"+typeAffichage+"-lignes");
}

function afficherOnglets() {
        var $tabs = $('#obs').tabs();
        $('#obs').bind('tabsselect', function(event, ui) {
                if (ui.panel.id == 'obs-vue-tableau') {
                        surClicAffichageTableau();
                } else if (ui.panel.id == 'obs-vue-liste') {
                        surClicAffichageListe();
                }
        });
        if (obsJSON.total > 4) {
                surClicAffichageTableau();
        } else {
                $tabs.tabs('select', "#obs-vue-liste");
        }
}

function surClicAffichageTableau() {
        typeAffichage = 'tableau';
        selectionnerOnglet();
        ajouterObservationsDansHTML();
        mettreAJourTableauTriable("#obs-tableau");
}

function surClicAffichageListe() {
        typeAffichage = 'liste';
        selectionnerOnglet();
        ajouterObservationsDansHTML();
}

function ajouterTableauTriable(element) {
        // add parser through the tablesorter addParser method 
        $.tablesorter.addParser({ 
                // Définition d'un id unique pour ce parsseur 
                id: 'date_cel', 
                is: function(s) { 
                        // doit retourner false si le parsseur n'est pas autodétecté
                        return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
                }, 
                format: function(date) { 
                        // Transformation date jj/mm/aaaa en aaaa/mm/jj
                        date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
                        // Remplace la date par un nombre de millisecondes pour trier numériquement
                        return $.tablesorter.formatFloat(new Date(date).getTime());
                }, 
                // set type, either numeric or text 
                type: 'numeric' 
        });
        $(element).tablesorter({ 
        headers: { 
                        1: { 
                sorter:'date_cel' 
                } 
        } 
        });
}

function mettreAJourTableauTriable(element) {
        $(element).trigger('update');
}

function afficherTexteStationId() {
        var latitude = pointClique.getLatLng().lat;
        var longitude = pointClique.getLatLng().lng;
        var texteStationId = pointClique.options.type + ':' + latitude + '|' + longitude;
        $('#obs-station-id').text(texteStationId);
}