/tags/v0.1-y/modules/nettoyage_kml/NettoyageKml.php |
---|
New file |
0,0 → 1,150 |
<?php |
// declare(encoding='UTF-8'); |
/** |
* Exemple de script utilisable avec le TBFramework. |
* Pour le lancer, taper en ligne de commande, en vous plaçant dans le dossier /framework/exemple/scripts/ : |
* <code>/opt/lampp/bin/php cli.php mon_script -a test</code> |
* |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2010, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3 |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2 |
* @version $Id$ |
*/ |
class NettoyageKml extends Script { |
private $fichier_id = ''; |
private $coordonnees_simples = array(); |
protected $parametres_autorises = array( |
'-f' => array(true, true, 'Fichier KML à nettoyer.')); |
public function executer() { |
// Récupération de paramêtres |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'nettoyer' : |
$this->executerNettoyage(); |
break; |
default : |
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd)); |
} |
} |
private function executerNettoyage() { |
$kml = $this->getParametre('f'); |
if (file_exists($kml)) { |
$placemarks = $this->analyserFichierKml($kml); |
$nom_kml = basename($kml, '.kml'); |
$dossier_kml = dirname($kml); |
$dpt = '00'; |
if (preg_match('/^([0-9]{2})/', $nom_kml, $match)) { |
$dpt = $match[1]; |
} |
$fichier_sortie = $dossier_kml.DS.$dpt.'%s.kml'; |
$squelette = dirname(__FILE__).DS.'squelettes'.DS.'defaut.tpl.kml'; |
$num = 1; |
$pas = Config::get('fichierSortie.taille'); |
$taille = 0; |
$nbre_placemarks = count($placemarks); |
foreach ($placemarks as $id => $placemark) { |
$placemarks_portion[] = $placemark; |
$taille += mb_strlen($placemark); |
if ($taille > $pas || $id == ($nbre_placemarks - 1)) { |
$taille = 0; |
$donnees = array('nom' => $nom_kml, 'placemarks' => $placemarks_portion); |
$sortie = SquelettePhp::analyser($squelette, $donnees); |
$suffixe_fichier = ($id == ($nbre_placemarks - 1) && $num == 1) ? '' : '_'.$num++; |
if (file_put_contents(sprintf($fichier_sortie, $suffixe_fichier), $sortie)) { |
@chmod($fichier_sortie, octdec(Config::get('fichierSortie.droits'))); |
} else { |
trigger_error("Impossible d'écrire dans le fichier : $fichier_sortie", E_USER_WARNING); |
} |
$placemarks_portion = array(); |
} |
} |
} |
} |
private function analyserFichierKml($fichier_kml) { |
$placemarks = array(); |
$lignesKML = file($fichier_kml, FILE_SKIP_EMPTY_LINES); |
foreach ($lignesKML as $id => $ligne) { |
if (preg_match('/^\s*<Placemark>/', $ligne)) { |
if (isset($placemark)) { |
$placemarks[] = $placemark; |
} |
$placemark = ''; |
} |
$this->trouverFichierId($ligne); |
if (isset($placemark)) { |
$ligne = $this->remplacerChaines($ligne); |
$placemark .= $this->traiterLigne($ligne); |
} |
} |
return $placemarks; |
} |
private function trouverFichierId($ligne) { |
if (preg_match('/<Document><Folder><name>([^<]+)<\/name>/', $ligne, $match)) { |
$this->fichier_id = $match[1]; |
} |
} |
private function remplacerChaines($ligne) { |
$ligne = preg_replace("/^\s+(<[\/]?Placemark>)/", "\t\t$1", $ligne); |
$ligne = preg_replace("/^\s+(<name>)/", "\t\t\t$1", $ligne); |
$ligne = preg_replace("/(<ExtendedData>)(<SchemaData)/", "\t\t$1\n\t\t\t\t$2", $ligne); |
$ligne = preg_replace("/(<\/SchemaData>)(<\/ExtendedData>)/", "\t\t\t$1\n\t\t\t$2", $ligne); |
$ligne = preg_replace('/^\t+(<SimpleData name=")CODE_INSEE(">)/', "\t\t\t\t\t$1code_insee$2", $ligne); |
$ligne = preg_replace('/(schemaUrl="#)'.$this->fichier_id.'(")/', "$1commune$2", $ligne); |
return $ligne; |
} |
private function traiterLigne($ligne) { |
$ligne_traitee = $ligne; |
if (preg_match('/^\s*(<Polygon><outerBoundaryIs><LinearRing><coordinates>)([^<]+)([^$]+)/', $ligne, $match)) { |
$debut_chaine_polygone = $match[1]; |
$coordonnees = $this->traiterCoordonnees($match[2]); |
$fin_chaine_polygone = $match[3]; |
$ligne_traitee = "\t\t\t".$debut_chaine_polygone.$coordonnees.$fin_chaine_polygone; |
} else if (preg_match('/^\s*<Style>.*<\/Style>$/u', $ligne)) { |
$url_style = Config::get('urlStyle'); |
$ligne_traitee = "\t\t\t<styleUrl>$url_style#commune-limite</styleUrl>\n"; |
} else if (preg_match('/^\t+<SimpleData name="Name">/', $ligne)) { |
// Ne pas prendre en compte cette ligne |
} else { |
$ligne_traitee = $ligne; |
} |
return $ligne_traitee; |
} |
private function traiterCoordonnees($chaine_coordonnees) { |
$coordonnees = explode(' ', $chaine_coordonnees); |
$geo_points = array(); |
foreach ($coordonnees as $coord) { |
list($lon, $lat) = explode(',', $coord); |
$geo_points[] = new GeoPoint($lat, $lon); |
} |
$reducteur = new PolylineReducer($geo_points); |
$coordonnees_simplifiees = $reducteur->SimplerLine(Config::get('simplification')); |
$polygone_points = array(); |
foreach ($coordonnees_simplifiees as $geoPoint) { |
$lat = str_replace(',', '.', $geoPoint->latitude); |
$lon = str_replace(',', '.', $geoPoint->longitude); |
$polygone_points[] = $lon.','.$lat; |
} |
$this->traiterInfo("Traitement coordonnées (avt/aprs) : %s/%s", array(count($coordonnees), count($coordonnees_simplifiees))); |
return implode(' ', $polygone_points); |
} |
} |
?> |
/tags/v0.1-y/modules/nettoyage_kml/squelettes/defaut.tpl.kml |
---|
New file |
0,0 → 1,22 |
<?='<?xml version="1.0" encoding="utf-8"?>'."\n"?> |
<!-- Source : openstreetmap : http://wiki.openstreetmap.org/wiki/WikiProject_France/Fonds_de_cartes/Contours_de_Communes_au_format_vecteur --> |
<kml xmlns="http://earth.google.com/kml/2.2"> |
<Document> |
<name><![CDATA[<?=$nom?>]]></name> |
<Style id="commune-limite"> |
<LineStyle> |
<width>0.8</width> |
<color>ff956195</color> |
</LineStyle> |
<PolyStyle> |
<fill>0</fill> |
</PolyStyle> |
</Style> |
<Schema name="commune" id="commune"> |
<SimpleField name="code_insee" type="string"></SimpleField> |
</Schema> |
<? foreach ($placemarks as $placemark) : ?> |
<?=$placemark?> |
<? endforeach ?> |
</Document> |
</kml> |
/tags/v0.1-y/modules/nettoyage_kml/config.ini |
---|
New file |
0,0 → 1,10 |
; Fichier de style à utiliser pour les fichiers KML : |
; la référence à un style externe ne fonctionnant pas avec les KMZ, |
; les styles sont directement dans le squelette |
urlStyle = "";http://www.tela-botanica.org/eflore/cel2/widget/modules/carto/squelettes/kml/styles.kml |
; Droits des fichiers de sortie créé par le script |
fichierSortie.droits = "0775" |
; Taille en octets des fichiers de sortie |
fichierSortie.taille = 2750000 |
; Niveau de simplification (plus le nombre est grand plus vous augmenter la simplification) |
simplification = 0.0001 |
/tags/v0.1-y/configurations/config.ini |
---|
New file |
0,0 → 1,23 |
; +------------------------------------------------------------------------------------------------------+ |
; Général |
; Séparateur de dossier |
ds = DIRECTORY_SEPARATOR |
; +------------------------------------------------------------------------------------------------------+ |
; Info sur l'application |
info.nom = Communes |
; Abréviation de l'application |
info.abr = COM |
; Version du Framework nécessaire au fonctionnement de cette application |
info.framework.version = 0.3 |
;Encodage de l'application |
appli_encodage = "UTF-8" |
;Chemin de l'application (pour l'utiliser dans ce fichier) |
chemin_scripts = "php:Framework::getCheminAppli()" |
; +------------------------------------------------------------------------------------------------------+ |
; Débogage |
; Indique si oui ou non on veut afficher le débogage. |
fw_debogage = true |
; Indique si oui ou non on veut lancer le chronométrage |
benchmark_chrono = false |
/tags/v0.1-y/framework.defaut.php |
---|
New file |
0,0 → 1,6 |
<?php |
// Inclusion du Framework |
// Renomer ce fichier en "framework.php" |
// Indiquyer ci-dessous le chemin absolu vers le fichier autoload.inc.php de la bonne version du Framework |
require_once '../../framework/Framework.php'; |
?> |
/tags/v0.1-y/bibliotheque/Vector.php |
---|
New file |
0,0 → 1,26 |
<?php |
class Vector { |
public $x; |
public $y; |
public $include; |
public function __construct($x,$y) { |
$this->x = $x; |
$this->y = $y; |
} |
public function DotProduct(Vector $v) { |
$dot = ($this->x * $v->x + $this->y * $v->y); |
return $dot; |
} |
public function Magnitude() { |
return sqrt($this->x*$this->x + $this->y*$this->y); |
} |
public function UnitVector() { |
if ($this->Magnitude() == 0) return new Vector(0,0); |
return new Vector($this->x / $this->Magnitude(), $this->y / $this->Magnitude()); |
} |
} |
?> |
/tags/v0.1-y/bibliotheque/GeoPoint.php |
---|
New file |
0,0 → 1,11 |
<?php |
class GeoPoint { |
public $latitude; |
public $longitude; |
public function __construct($lat, $lng) { |
$this->latitude = (float) $lat; |
$this->longitude = (float) $lng; |
} |
} |
?> |
/tags/v0.1-y/bibliotheque/PolylineReducer.php |
---|
New file |
0,0 → 1,85 |
<?php |
/*======================================================== |
/* Implementation of Douglas-Peuker in PHP. |
/* |
/* Anthony Cartmell |
/* ajcartmell@fonant.com |
/* |
/* This software is provided as-is, with no warranty. |
/* Please use and modify freely for anything you like :) |
/* Version 1.2 - 18 Aug 2009 Fixes problem with line of three points. |
/* Thanks to Craig Stanton http://craig.stanton.net.nz |
/* Version 1.1 - 17 Jan 2007 Fixes nasty bug! |
/*========================================================*/ |
class PolylineReducer { |
private $original_points = array(); |
private $tolerance; |
private $tolerance_squared; |
public function __construct($geopoints_array) { |
foreach ($geopoints_array as $point) { |
$this->original_points[] = new Vector($point->latitude, $point->longitude); |
} |
/*----- Include first and last points -----*/ |
$this->original_points[0]->include = true; |
$this->original_points[count($this->original_points)-1]->include = true; |
} |
/** |
* Returns a list of GeoPoints for the simplest polyline that leaves |
* no original point more than $tolerance away from it. |
* |
* @param float $tolerance |
* @return Geopoint array |
*/ |
public function SimplerLine($tolerance = 0.5) { |
$this->tolerance = $tolerance; |
$this->tolerance_squared = $tolerance * $tolerance; |
$this->DouglasPeucker(0, count($this->original_points) - 1); |
foreach ($this->original_points as $point) { |
if ($point->include) { |
$out[] = new GeoPoint($point->x, $point->y); |
} |
} |
return $out; |
} |
/** |
* Douglas-Peuker polyline simplification algorithm. First draws single line |
* from start to end. Then finds largest deviation from this straight line, and if |
* greater than tolerance, includes that point, splitting the original line into |
* two new lines. Repeats recursively for each new line created. |
* |
* @param int $start_vertex_index |
* @param int $end_vertex_index |
*/ |
private function DouglasPeucker($start_vertex_index, $end_vertex_index) { |
if ($end_vertex_index <= $start_vertex_index + 1) // there is nothing to simplify |
return; |
// Make line from start to end |
$line = new Line($this->original_points[$start_vertex_index], $this->original_points[$end_vertex_index]); |
// Find largest distance from intermediate points to this line |
$max_dist_to_line_squared = 0; |
for ($index = $start_vertex_index+1; $index < $end_vertex_index; $index++) { |
$dist_to_line_squared = $line->DistanceToPointSquared($this->original_points[$index]); |
if ($dist_to_line_squared>$max_dist_to_line_squared) { |
$max_dist_to_line_squared = $dist_to_line_squared; |
$max_dist_index = $index; |
} |
} |
// Check max distance with tolerance |
if ($max_dist_to_line_squared > $this->tolerance_squared) {// error is worse than the tolerance |
// split the polyline at the farthest vertex from S |
$this->original_points[$max_dist_index]->include = true; |
// recursively simplify the two subpolylines |
$this->DouglasPeucker($start_vertex_index,$max_dist_index); |
$this->DouglasPeucker($max_dist_index,$end_vertex_index); |
} |
// else the approximation is OK, so ignore intermediate vertices |
} |
} |
?> |
/tags/v0.1-y/bibliotheque/Line.php |
---|
New file |
0,0 → 1,35 |
<?php |
class Line { |
public $p1; |
public $p2; |
public function __construct(Vector $p1,Vector $p2) { |
$this->p1 = $p1; |
$this->p2 = $p2; |
} |
public function LengthSquared() { |
$dx = $this->p1->x - $this->p2->x; |
$dy = $this->p1->y - $this->p2->y; |
return $dx*$dx + $dy*$dy; |
} |
public function DistanceToPointSquared(Vector $point) { |
$v = new Vector($point->x - $this->p1->x, $point->y - $this->p1->y); |
$l = new Vector($this->p2->x - $this->p1->x, $this->p2->y - $this->p1->y); |
$dot = $v->DotProduct($l->UnitVector()); |
if ($dot <= 0) {// Point nearest P1 |
$dl = new Line($this->p1, $point); |
return $dl->LengthSquared(); |
} |
if (($dot*$dot)>=$this->LengthSquared()) {// Point nearest P2 |
$dl = new Line($this->p2, $point); |
return $dl->LengthSquared(); |
} else {// Point within line |
$v2 = new Line($this->p1, $point); |
$h = $v2->LengthSquared(); |
return $h - $dot * $dot; |
} |
} |
} |
?> |
/tags/v0.1-y/cli.php |
---|
New file |
0,0 → 1,37 |
<?php |
// Encodage : UTF-8 |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Initialise le chargement et l'exécution des scripts |
* |
* Lancer ce fichier en ligne de commande avec : |
* <code>/opt/lampp/bin/php cli.php mon_script -a test</code> |
* |
//Auteur original : |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @author Delphine CAUQUIL <delphine@tela-botanica.org> |
* @copyright Tela-Botanica 1999-2008 |
* @licence GPL v3 & CeCILL v2 |
* @version $Id$ |
*/ |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Le fichier autoload.inc.php du Framework de Tela Botanica doit être appelée avant tout autre chose dans l'application. |
// Sinon, rien ne sera chargé. |
// Chemin du fichier chargeant le framework requis |
$framework = dirname(__FILE__).DIRECTORY_SEPARATOR.'framework.php'; |
if (!file_exists($framework)) { |
$e = "Veuillez paramétrer l'emplacement et la version du Framework dans le fichier $framework"; |
trigger_error($e, E_USER_ERROR); |
} else { |
// Inclusion du Framework |
require_once $framework; |
// Ajout d'information concernant cette application |
Framework::setCheminAppli(__FILE__);// Obligatoire |
Framework::setInfoAppli(Config::get('info')); |
// Initialisation et lancement du script appelé en ligne de commande |
Cli::executer(); |
} |
?> |
/tags/v0.1-y/communeShp2kml.sh |
---|
New file |
0,0 → 1,98 |
#/bin/bash |
######################################################################################################################## |
# But : mise en ligne automatique sur le serveur par ftp, des derniers contour de communes d'OSM au format KMZ |
# Auteur : Jean-Pascal Milcent <jpm@clapas.org> (translate bat file to shell script) |
# License : GPL v3 |
# Création : 28 décembre 2010 |
# Version: 0.1 |
# $Id$ |
######################################################################################################################## |
# Constante |
NBREPARAM=$# |
DOSSIER_DEPOT="/home/jpm/Documents/Cartographie/Communes/" |
DOSSIER_TELECHARGEMENT="${DOSSIER_DEPOT}Telechargements/" |
DOSSIER_EXTRACTION="${DOSSIER_DEPOT}Extraction/" |
DOSSIER_LOCAL_KMZ="${DOSSIER_DEPOT}Kmz" |
DOSSIER_DESTINATION="/www/eflore/cel2/widget/modules/carto/squelettes/kml" |
LOG="${DOSSIER_DEPOT}log.txt" |
BASE_URL="http://beta.letuffe.org/ressources/export-communes/" |
EXT="*.shp.tar.gz" |
# Aide |
E_OPTERR=65 |
if [ "$1" = '--help' ] |
then # Le script a besoin d'au moins un argument sur la ligne de commande |
echo "Usage $0 -[parameters -u, -p ]" |
echo "Paramètres : " |
echo " -h: indiquer l'hote ftp" |
echo " -u: indiquer le nom de l'utilisateur ftp" |
echo " -p: indiquer le mot de passe de l'utilisateur ftp" |
exit $E_OPTERR |
fi |
# Récupération des paramètres et des options de la ligne de commande |
TEMP=`getopt -o u:p:h: -l help: -- "$@"` |
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi |
eval set -- "$TEMP" |
while [ ! -z "$1" ] ; do |
#echo $1" # "$2 |
case "$1" in |
-h) HOST=$2;; |
-u) FTP_USER=$2;; |
-p) FTP_PASSWD=$2;; |
--) shift ; break ;; |
*) echo "Internal error!" ; exit 1 ;; |
esac |
shift 2 |
done |
rm -fR $DOSSIER_EXTRACTION |
mkdir $DOSSIER_EXTRACTION |
rm -fR $DOSSIER_LOCAL_KMZ |
mkdir $DOSSIER_LOCAL_KMZ |
echo "Téléchargement des derniers fichiers shape en cours..."; |
wget -A "$EXT" -P $DOSSIER_TELECHARGEMENT -o $LOG -N -v -i $BASE_URL |
echo "Extraction des fichiers en cours..."; |
cd $DOSSIER_EXTRACTION |
for f in $DOSSIER_TELECHARGEMENT$EXT; do |
d=`basename $f .shp.tar.gz` |
mkdir $d |
(cd $d && tar xf $f) |
done |
for dossier in $DOSSIER_EXTRACTION/*; do |
#dossier="${DOSSIER_EXTRACTION}01-Ain" |
if [ -d $dossier ]; then |
nom_dpt=`basename $dossier` |
echo "Dossier : $nom_dpt"; |
fichier_kml="$dossier/${nom_dpt}.kml" |
fichier_shp="$dossier/${nom_dpt}.shp" |
#echo "Nom dpt : $nom_dpt"; |
for fichier in $dossier/*; do |
if [ -f $fichier ]; then |
if [ "$fichier" == "$fichier_shp" ]; then |
rm -f "$dossier/*.km*" |
ogr2ogr -f KML $fichier_kml $fichier_shp $nom_dpt |
/opt/lampp/bin/php ~/web/communes/cli.php nettoyage_kml -a nettoyer -f $fichier_kml |
fi |
fi |
done |
for fichier in $dossier/*; do |
if [ -f $fichier ]; then |
if [[ "$fichier" != "$fichier_kml" && $fichier == *.kml ]]; then |
nom_kml=`basename $fichier .kml` |
fichier_kmz="${dossier}/${nom_kml}.kmz" |
echo "KMZ : $fichier_kmz"; |
zip -j9 -r $fichier_kmz $fichier |
mv $fichier_kmz $DOSSIER_LOCAL_KMZ |
fi |
fi |
done |
fi |
done |
if [ $NBREPARAM -eq 0 ]; then |
echo "Pas de transfert sur le serveur. Utiliser --help pour voir les options de transfert." |
else |
lftp ftp://$FTP_USER:$FTP_PASSWD@$HOST -e "set ftp:passive off; mirror -e -R -L -x .svn $DOSSIER_LOCAL_KMZ $DOSSIER_DESTINATION ; quit" |
fi |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
Added: svn:executable |
/tags/v0.1-y/. |
---|
New file |
Property changes: |
Added: svn:ignore |
+framework.php |
+.buildpath |
+.project |